这里是另一种方法,仍然代表帐户作为封闭,但不会改变balance
。相反,deposit
和withdraw
会返回新的帐户关闭。
(defn account
[name balance password]
(fn [msg & args]
(case msg
:name name
:balance balance
:deposit (account name (- balance (first args)) password)
:withdraw (account name (+ balance (first args)) password)
:authenticate (= password (first args)))))
由于例如(person :deposit 50)
返回一个新的结算信息,而不是新的余额,您需要使用:balance
来电/信息来查看结果余额是多少。
(def person (account "name" 100 "password"))
(person :deposit 50) ; returns a new closure
;=> #<user$account$fn__85647 [email protected]>
(person :balance) ; our original `person` still has its original balance
;=> 100
((person :deposit 50) :balance) ; but a new closure can have a new balance
;=> 150
来源
2013-11-21 03:56:32
jbm
相反condp'的',你可能需要使用['case'(http://clojuredocs.org/clojure_core/clojure.core/case),这是一个小更简洁(但只适用当你只是比较编译时常量,如关键字)。 – DaoWen