我一直在Structure and Interpretation of Computer Programs中完成並完成Haskell中的練習。前兩章沒有問題(代碼爲github),但第3章讓我更加難以思考。管理狀態 - SICP第3章
它首先討論管理狀態,以銀行賬戶爲例。他們通過
(define (make-withdraw balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds")))
定義一個函數make-withdraw
讓你可以執行以下代碼:
(define w1 (make-withdraw 100))
(define w2 (make-withdraw 100))
(w1 50)
50
(w2 70)
30
(w2 40)
"Insufficient funds"
(w1 40)
10
我不知道我怎麼能在Haskell模擬此。我首先想到的使用狀態單子一些簡單的功能:
import Control.Monad.State
type Cash = Float
type Account = State Cash
withdraw :: Cash -> Account (Either String Cash)
withdraw amount = state makewithdrawal where
makewithdrawal balance = if balance >= amount
then (Right amount, balance - amount)
else (Left "Insufficient funds", balance)
,讓我來運行代碼
ghci> runState (do { withdraw 50; withdraw 40 }) 100
(Left "Insufficient funds",30.0)
但做一些事情的方式不同代碼。理想情況下我可以運行類似
do
w1 <- makeWithdraw 100
w2 <- makeWithdraw 100
x1 <- w1 50
y1 <- w2 70
y2 <- w2 40
x2 <- w1 40
return [x1,y1,y2,x2]
[Right 50,Right 70,Left "Insufficient funds",Right 40]
,但我不知道怎麼寫功能makeWithdraw
。有什麼建議?
謝謝,這是一個很好的答案。 – 2012-04-06 21:04:07