Jim*_*ron 0 lisp scheme sbcl common-lisp mit-scheme
在我的一本书中,我有这个方案代码,并想将其转换为 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)
Run Code Online (Sandbox Code Playgroud)
然后我将使用以下命令创建它:
(define acc (make-account 1500))
Run Code Online (Sandbox Code Playgroud)
然后调用deposit或withdraw:
((acc 'withdraw) 50)
或者
((acc 'deposit) 75)
据我了解,
acc被函数替换dispatch并返回withdrawordeposit
然后计算表达式,例如:
((acc 'withdraw) 50)-> ((dispatch 'withdraw) 50)->(withdraw 50)
现在,我如何将这个程序和逻辑转换为 Common Lisp。我感谢您的帮助。
The basic structure is the same, but you use FLET or LABELS to define local functions within a function. In this case you need to use LABELS because the functions refer to each other.
In Common Lisp you have to use FUNCALL to call functions dynamically. This makes this style of functional programming inconvenient; Common Lisp programmers generally use DEFSTRUCT or CLOS.
(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)
Run Code Online (Sandbox Code Playgroud)