我正在阅读 Graham Hutton 的(伟大的)书的第二版 "Progamming in Haskell" (剑桥出版社)。
阅读 State Monad 部分时,我偶然发现了一个给自己的小任务。
如何使用 where
而不是 let
重写以下内容?
type State = Int
newtype ST a = S (State -> (a, State))
instance Functor ST where
-- fmap :: (a -> b) -> ST a -> ST b
fmap g st = S (\state -> let (x, s') = app st state in (g x, s'))
我尝试了此代码的变体,但它不起作用:
instance Functor ST where
-- fmap :: (a -> b) -> ST a -> ST b
fmap g st = S (\state -> (g x, newstate))
where (x, newstate) = app st state
我知道它本身没有用,但我想知道它是否以及如何可能。
最佳答案
let BINDINGS in EXPRESSION
是一个表达式,可以在允许表达式的任何地方使用。
where
仅附加到声明,而不附加到表达式。 \state -> ...
不是声明,因此您无法将 where
附加到它。您也不能将其附加到外部声明,因为这样 state
将不在范围内。
可能的解决方案:
instance Functor ST where
fmap g st = S f
where
f state = (g x, s')
where (x, s') = app st state
我们有一个本地声明 f state = ...
,而不是匿名函数 \state -> ...
,我们可以在其上附加一个 有权访问
子句。state
的 where
关于haskell - Haskell 中 lambda 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959598/