2013-04-02 98 views
0

我必须编写一个程序,将字符串的元音,辅音和其他符号分别转换为C,V和0.我已经完成了这项工作,但我想知道是否有更高效和更优雅的方法来执行此操作。将不胜感激输入。LISP - 修改字符串

(defun string-to-list (string) 
(loop for char across string collect char)) 

(defun is-vowel (char) (find char "aeiou" :test #'char-equal)) 

(defun is-consonant (char) (find char "bcdfghjklmnpqrstvwxyz" :test #'char-equal)) 

(defun letter-type (char) 
(if (is-vowel char) "V" 
(if (is-consonant char) "C" 
"0"))) 

(defun analyze-word (word-string) 
(loop for char across word-string collect (letter-type char))) 

此外,我想使它成为一个字符串,我怎么能做到这一点?我应该定义一个函数来遍历列表并将其设置为一个字符串,还是更简单的方法?

+1

这个问题应该得到更好的http://codereview.stackexchange.com/问 – akluth

+0

使用“地图”来代替。如果你的格式和按照典型惯例缩进你的代码,这将会有所帮助。 –

+0

我不知道如何使用'MAP',你能帮我吗? –

回答

2
(defun letter-type (char) 
    (cond ((find char "aeiou" :test #'char-equal) #\V) 
     ((alpha-char-p char) #\C) 
     (t #\0))) 

CL-USER> (map 'string #'letter-type "analyze-word") 
"VCVCCCV0CVCC" 
+0

虽然当我输入“spectacuular22ace”它给了我“VCVCCCV0CVCC”,壮观的AV开头是一个辅音而不是一个元音,并且超过了它,它只打印一个0而不是两个0. –

+1

您必须更换“分析在上面的示例中输入了“-word”。 – huaiyuan

0

只是为理念的缘故:

(defun multi-replace-if (sequence function &rest more-functions) 
    (map (type-of sequence) 
     (lambda (x) 
     (loop for f in (cons function more-functions) 
      for result = (funcall f x) 
      while (eql x result) 
      finally (return result))) 
     sequence)) 

(multi-replace-if "bcdfghjklmnpqrstvwxyz" 
        (lambda (x) (if (find x "aeiouy") #\v x)) 
        (lambda (y) (declare (ignore y)) #\c)) 
"cccccccccccccccccccvc"