Skip to content

Instantly share code, notes, and snippets.

@Liutos
Created August 17, 2012 02:31
Show Gist options
  • Save Liutos/3375408 to your computer and use it in GitHub Desktop.
Save Liutos/3375408 to your computer and use it in GitHub Desktop.
计算字符串中单词个数的函数word-count
(defun same-kind-chars (c1 c2)
(or (and (alpha-char-p c1)
(alpha-char-p c2))
(and (not (alpha-char-p c1))
(not (alpha-char-p c2)))))
(defun singleton-list (list)
(and list (null (cdr list))))
;;; 普通递归版本
(defun word-count (str)
(labels ((aux (s)
(cond ((null s) 0)
((and (singleton-list s)
(not (alpha-char-p (car s)))) 0)
((and (singleton-list s)
(alpha-char-p (car s))) 1)
(t (+ (aux (cdr s))
(if (and (not (same-kind-char (car s) (cadr s)))
(char/= (car s) #\Space))
1 0))))))
(aux (coerce str 'list))))
;;; 尾递归版本
(defun word-count (str)
(labels ((aux (cnt s)
(cond ((null s) cnt)
((and (singleton-list s)
(not (alpha-char-p (car s)))) cnt)
((and (singleton-list s)
(alpha-char-p (car s))) (1+ cnt))
(t (aux (+ cnt
(if (and (not (same-kind-char (car s) (cadr s)))
(char/= (car s) #\Space))
1 0))
(cdr s))))))
(aux 0 (coerce str 'list))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment