常见的Lisp映射到单词

时间:2019-03-13 00:25:18

标签: lisp common-lisp

我正在尝试制作一个转换函数,该函数接受一个数字列表((1 2 3)并写入(“一个”,“两个”,“三个”)。这是我到目前为止的内容:

(defun translate-number (num)
        (if (= num 0) (return "ZERO") ())
        (if (= num 1) (return "ONE") ())
        (if (= num 2) (return "TWO") ())
        (if (= num 3) (return "THREE") ())
        (if (= num 4) (return "FOUR") ())
        (if (= num 5) (return "FIVE") ())
        (if (= num 6) (return "SIX") ())
        (if (= num 7) (return "SEVEN") ())
        (if (= num 8) (return "EIGHT") ())
        (if (= num 9) (return "NINE") ())
)

(defun translate (L)
  (mapcar #'translate-number L)
)

(translate `(1 2 3))

如果我尝试运行此命令,则会收到无法弄清的错误消息:

*** - RETURN-FROM: no block named NIL is currently visible

有什么想法吗?谢谢。

2 个答案:

答案 0 :(得分:8)

return与其他语言不一样:]您在寻找return-from translate-number,但这不是惯用语言。

首先,您是否知道format函数具有~R“罗马”指令?

(format nil "~R" 1) ;; => one

如果您确实想要大写,请使用string-upcase或格式指令~( ... ~)及其修饰符@:

(format nil "~@:(~R~)" 1)
;; "ONE"

https://lispcookbook.github.io/cl-cookbook/strings.html#to-upper-case--

CL快速参考,其中包含格式指令:http://clqr.boundp.org/

所以:

(mapcar (lambda (nb) 
          (format nil "~@:(~R~)" nb))
        '(1 2 3))
("ONE" "TWO" "THREE")

连续if可以使用casecond

(defun translate-number (num)
   (case num
     (1 "ONE")
     (2 "FOO")))

第二种形式的()不需要空白if

https://learnxinyminutes.com/docs/common-lisp/;)

答案 1 :(得分:3)

CL-USER > (getf '(1 "ONE" 2 "TWO" 3 "THREE" 4 "FOUR" 5 "FIVE"
                  6 "SIX" 7 "SEVEN" 8 "EIGHT" 9 "NINE")
                2
                :dont-know)
"TWO"

CL-USER > (aref #("ZERO" "ONE" "TWO" "THREE" "FOUR"
                  "FIVE" "SIX" "SEVEN" "EIGHT" "NINE")
                2)
"TWO"