1

我仍然是 Clojure 的菜鸟,我知道我正在尝试解决涉及大学银行交易场景的问题。

问题很简单:我必须开发一个贷记、借记和转账的解决方案。

我停在这里:

(def account
    (ref 100))

(defn credit [account amount]
  "Credit"
  (dosync
    (alter account + amount)))


(defn debit [account amount]
  "Debit"
  (dosync
    (if (> amount (balance account))
      (throw (Exception. "Insuficient Funds"))
      (alter account - amount))))

(defn transfer [from to amount]
  "Transfer"
  (dosync
    (if (<= amount (balance from)) 
      (do 
        (Thread/sleep 10)
        (debit from amount)


        (credit to amount))
      (throw
        (Exception. "Insuficient Funds")))))

我认为这没什么难理解的,上面的代码正在运行。

我应该在上面的每个函数中添加帐号、交易描述、数据和金额以及内存中的存储,例如:

 (defn credit [account description data amount]
  "Credit"
  (dosync
    (alter account + amount)))

我尝试过使用哈希映射、向量和其他东西,但没有奏效。我也试图在这本书中找到这个解决方案:Clojure Programming O'reilly,但仍然难以实现。

感谢您抽出宝贵时间,如果您需要更多信息,请告诉我。

4

1 回答 1

1

我想我找到了一种方法来开发这个场景。

在创建银行账户时,我使用 refs 和一个结构来保存所有需要的数据(名称账户、数字账户和将创建的所有交易的操作列表)

(defn create-account [name account-number]
  "Create account"
  (ref (merge {:name name :account-number account-number :operations '()})))

(def joey 
  "Account for tests"
  (create-account "joey" 12345678))
于 2017-01-09T21:30:00.537 回答