Created
August 17, 2012 02:31
-
-
Save Liutos/3375408 to your computer and use it in GitHub Desktop.
计算字符串中单词个数的函数word-count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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