我想在lisp中編寫一個宏,它返回傳遞給它的第n個表達式,並且只評估該表達式。例如:Lisp宏評估表達式,當我不想要它
(let ((n 2))
(nth-expr n (/ 1 0) (+ 1 2) (/ 1 0)))
應該返回3.我得到一個除以0的錯誤。我的宏定義如下:
(defmacro nth-expr (n &rest expressions)
(let ((i (gensym))
(expr (gensym)))
`(do ((,i 1 (1+ ,i))
(,expr ,expressions (cdr ,expr)))
((= ,i ,n) (car ,expr)))))
任何想法我做錯了什麼?謝謝。
編輯:
感謝@Vsevolod Dyomkin幫我與上面的部分。現在還有一個問題。當我嘗試做
(let ((n 3) (x "win") (y "lose"))
(nth-expr n (princ x) (princ x) (princ y) (princ x)))
我得到錯誤Error: Attempt to take the value of the unbound variable 'Y'
。
我更新的代碼看起來是這樣的:
(defmacro nth-expr (n &rest expressions)
(let ((i (gensym))
(expr (gensym))
(num (gensym)))
`(let ((,num (eval ,n)))
(do ((,i 1 (1+ ,i))
(,expr ',expressions (cdr ,expr)))
((= ,i ,num) (eval (car ,expr)))))))
你爲什麼要在宏中調用'eval'? – leppie
@leppie,因爲如果我不這樣做,它會返回(princ y),但我希望對它進行評估。 – Daniel
'Y'在該階段不存在。你想做什麼? – leppie