将MIT Scheme代码逻辑转换为Common Lisp



在我的一本书中,我有这个方案代码,并想将其转换为Common Lisp:

(define (make-account balance)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(define (dispatch m)
(cond
((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUNT" m))))
dispatch)

然后我用创建它

(define acc (make-account 1500))

然后用调用CCD_ 1或CCD_

((acc 'withdraw) 50)

((acc 'deposit) 75)

据我所知acc被函数dispatch替换,并返回withdrawdeposit然后评估该表达式,例如:((acc 'withdraw) 50)->deposit0->(withdraw 50)

现在,我如何将这个程序和逻辑转换为Common Lisp。我感谢你的帮助。

基本结构相同,但使用FLETLABELS来定义函数中的局部函数。在这种情况下,您需要使用LABELS,因为函数是相互引用的。

在Common Lisp中,必须使用FUNCALL来动态调用函数。这使得这种类型的函数式编程不方便;常见的Lisp程序员通常使用DEFSTRUCTCLOS

(defun make-account (balance)
(labels
((withdraw (amount)
(if (>= balance amount)
(decf balance amount)
(error "Insufficient funds")))
(deposit (amount)
(incf balance amount))
(dispatch (m)
(cond
((eq m 'withdraw) #'withdraw)
((eq m 'deposit) #'deposit)
(t (error "Unknown request -- MAKE-ACCOUNT ~s" m))))))
#'dispatch)
(defvar acc (make-account 1500))
(funcall (funcall acc 'withdraw) 50)
(funcall (funcall acc 'deposit) 75)

最新更新