【发布时间】:2020-09-11 13:52:07
【问题描述】:
我目前在理解 Haskell 中的 Either-Monad 时遇到问题。 要么是 Monad 数据类型的一个实例。因此,我可以像这样在 Do 块中使用 Either ...
type MyAccount = Integer
transaction :: Integer -> MyAccount -> Either String MyAccount
transaction value account | value + account < 0 = Left "Error: insufficient funds!"
| otherwise = return $ account + value
Test1 :: Either String MyAccount
Test1 = do
account_state <- return 1000
r1 <- transaction (-200) account_state
r2 <- transaction (-1000) r1
return r2
这是一段代码:account_state、r1 和 r2 是整数类型。因此函数 transaction 可以正常工作。不过..
Test2 :: Either String MyAccount
Test2 = do
account_state <- return 1000
r1 <- transaction (-2000) account_state
r2 <- transaction (-1000) r1
return r2
在 Test2 中,我将交易价值从 -200 更改为 -2000。因此 r1 应该是字符串“错误:资金不足!”。由于 transaction 不适用于字符串,因此应该存在类型错误。但是没有... Haskell 在这里做什么?
事务 (-1000)(“错误:资金不足!”)不应该工作。
【问题讨论】:
-
我认为您可能错误地发布了错误的 sn-p:您的
Test2看起来几乎与Test1相同,除了-200被-2000替换。另请注意,这些都不应该编译,因为函数名不能大写。最后,没有“Monad 数据类型”之类的东西:Either是Monadtype class 的一个实例。 -
@FyodorSoikin 用
-2000替换-200正是重点:第一个不会透支帐户,第二个会。不过,您评论的其他部分仍然有效。 -
严格来说,
Either不能是 monad,因为它有一种Type -> Type -> Type;Either String可以是(并且是),因为它有一种Type -> Type。