2013-04-15 41 views
1

我試圖教自己一些LISP,雖然我理解它的大部分,但我很難理解eval函數。我知道它已經爲我們做了,它不好用(所以我聽到),但我怎麼才能做出一個剛添加的功能?LISP動態函數?

到目前爲止,我試圖/想

(setf input-prompt "Enter addition epression: ") 
(setf output-prompt "The value is: ") 

(defun prompt-for-input (msg) 
    (format t msg)) 


(defun sum (expression) 
    (format t "Summing ~d and ~d.~%" x y) 
    (+ x y)) 


(defun add() 
    (prompt-for-input input-prompt) 
    (let ((expression (read))) 
     ((sum (expression))) 
    (add))) 

不是真的知道該去哪裏這一點,任何幫助表示讚賞。

+0

你到底想幹什麼?這聽起來像你想根據你讀的表達式調用不同的函數,而不使用'eval'。這基本上是寫一個小解釋器,這是大多數Lisp書籍(Little Schemer等)所涵蓋的內容。但如果你能更清楚地描述你的問題,這將有所幫助。 –

回答

2
(setf input-prompt "Enter addition expression: ") 
(setf output-prompt "The value is: ") 

(defun prompt-for-input (msg) 
    (format t msg) 
    (finish-output)) 

(defun sum (expression) 
    (let ((x (second expression)) 
     (y (third expression))) 
    (format t "~%Summing ~d and ~d.~%" x y) 
    (+ x y))) 

(defun add() 
    (prompt-for-input input-prompt) 
    (sum (read))) 

運行:

CL-USER > (add) 
Enter addition expression: (+ 1 2) 
Summing 1 and 2. 
3 
+0

LISP如何去搞清楚「第二」和「第三」的表達是什麼? – Nogg

+0

''(第二個表達式)'是列表'表達式'的第二個元素。 – Svante

+0

代碼編譯後似乎不起作用。 – Nogg