2015-09-16 44 views

回答

-1

我能得到它的工作由字符串轉換爲一個符號:

(case (intern (string-upcase str)) 
    (a   "found an a") 
    (abc  "found an abc") 
    (otherwise "other")) 
+4

問題的一個典型來源:您最好告訴'INTERN'它應該使用哪個包 - 否則它將使用'* package *'的運行時值。 –

+6

即使如此,對於任意輸入「str」值,在運行過程的整個生命週期中,您都會保留**每個**不同的實際符號,實質上是內存泄漏。 – acelent

1

一個微不足道的(和潛在的慢)變種會是這樣的:

(defmacro string-case (str &rest forms) 
    (let* ((strval (gensym "STRVAL")) 
     (cond-body (loop for (s . f) in forms 
          collect `((string= ,strval ,s) ,@f)))) 
    `(let ((,strval ,str)) (cond ,@cond-body)))) 

這(不幸)不允許使用elseotherwise或字符串分組,但是使該擴展應該非常簡單。使用quicklisp中的現有字符串可能是更好的選擇。通過塞貝爾

(switch (str :test #'equal) 
    ("a" "found an a") 
    ("abc" "found an abc") 
    (t "other")) 
+0

謝謝!我使用了一個修改版本的這個基本的* CL兼容的Lisp變體。 –

8

亞歷山大有宏switchcswitcheswitch。這對我使用簡單的字符「A」「B」等是很有效的。要查看字符和字符串實際上是在嘗試使用(格式nil「〜:C」c)c是字符還是(格式nil「〜:S」s) s是串。

(defun prompt-read(prompt) 
    (format *query-io* "~a: " prompt) 
    (force-output *query-io*) 
    (read-char *query-io*)) 
(defun move() 
    (case(prompt-read "ROW[A-C]") 
    (#\A (print "A")) 
    (#\B (print "B")) 
    (#\C (print "C")))) 
0

這是從實用Common Lisp的只有正在使用的讀取字符,而不是讀行所做的更改: