我一直在Structure and Interpretation of Computer Programs工作并完成Haskell的练习。前两章很好(代码在github),但第3章让我更难思考。
首先谈论管理国家,以银行账户为例。他们通过
定义函数make-withdraw
(define (make-withdraw balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds")))
以便您可以执行以下代码:
(define w1 (make-withdraw 100))
(define w2 (make-withdraw 100))
(w1 50)
50
(w2 70)
30
(w2 40)
"Insufficient funds"
(w1 40)
10
我不确定如何在Haskell中模仿这个。我首先想到了一个使用State monad的简单函数:
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
。有什么建议吗?
答案 0 :(得分:8)
Scheme代码偷偷地使用两位状态:一个是变量w1
和w2
之间的(隐式)关联和ref-cell;另一个是存储在ref-cell中的(显式)状态。在Haskell中有几种不同的方法可以对其进行建模。例如,我们可能会使用ST
:
makeWithdraw :: Float -> ST s (Float -> ST s (Either String Float))
makeWithdraw initialBalance = do
refBalance <- newSTRef initialBalance
return $ \amount -> do
balance <- readSTRef refBalance
let balance' = balance - amount
if balance' < 0
then return (Left "insufficient funds")
else writeSTRef refBalance balance' >> return (Right balance')
让我们这样做:
*Main> :{
*Main| runST $ do
*Main| w1 <- makeWithdraw 100
*Main| w2 <- makeWithdraw 100
*Main| x1 <- w1 50
*Main| y1 <- w2 70
*Main| y2 <- w2 40
*Main| x2 <- w1 40
*Main| return [x1,y1,y2,x2]
*Main| :}
[Right 50.0,Right 30.0,Left "insufficient funds",Right 10.0]
另一种选择是明确显示状态的两个部分,例如将每个帐户与唯一的Int
ID相关联。
type AccountNumber = Int
type Balance = Float
data BankState = BankState
{ nextAccountNumber :: AccountNumber
, accountBalance :: Map AccountNumber Balance
}
当然,我们基本上会重新实施ref-cell操作:
newAccount :: Balance -> State BankState AccountNumber
newAccount balance = do
next <- gets nextAccountNumber
modify $ \bs -> bs
{ nextAccountNumber = next + 1
, accountBalance = insert next balance (accountBalance bs)
}
return next
withdraw :: Account -> Balance -> State BankState (Either String Balance)
withdraw account amount = do
balance <- gets (fromMaybe 0 . lookup account . accountBalance)
let balance' = balance - amount
if balance' < 0
then return (Left "insufficient funds")
else modify (\bs -> bs { accountBalance = insert account balance' (accountBalance bs) }) >> return (Right balance')
然后让我们写makeWithdraw
:
makeWithDraw :: Balance -> State BankState (Balance -> State BankState (Either String Balance))
makeWithdraw balance = withdraw <$> newAccount balance
答案 1 :(得分:4)
嗯,这里有多个独立的,可变的状态:一个用于系统中的每个“帐户”。 State
monad只允许您拥有一个状态。您可以在状态中存储类似(Int, Map Int Cash)
的内容,递增Int
以便每次都将新密钥放入地图中,并使用它来存储余额...但这太丑了,不是它?
幸运的是,Haskell有一个monad用于多个独立的,可变的状态:ST
。
type Account = ST
makeWithdraw :: Cash -> Account s (Cash -> Account s (Either String Cash))
makeWithdraw amount = do
cash <- newSTRef amount
return withdraw
where
withdraw balance
| balance >= amount = do
modifySTRef cash (subtract amount)
return $ Right amount
| otherwise = return $ Left "Insufficient funds"
有了这个,你的代码示例应该可以正常工作;只需应用runST
即可获得所需的列表。 ST
monad很简单:你可以创建和修改STRef
,它就像常规的可变变量一样;事实上,他们的界面基本上与IORef
的界面相同。
唯一棘手的一点是额外的s
类型参数,称为状态线程。这用于将每个STRef
与其创建的ST
上下文相关联。如果您可以从STRef
操作返回ST
并执行此操作,那将非常糟糕跨越另一个 ST
上下文 - ST
的全部内容是您可以在IO
之外将其作为纯代码运行,但如果STRef
s可以逃脱,你可以在monadic上下文之外有一个不纯的,可变的状态,只需将你的所有操作包装在runST
中!因此,每个ST
和STRef
都带有相同的s
类型参数,而runST
的类型为runST :: (forall s. ST s a) -> a
。这会阻止您为s
选择任何特定值:您的代码必须使用s
的所有可能值。从未分配任何特定类型;仅用作保持状态线程隔离的技巧。