我正在阅读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
而不是匿名函数\state -> ...
我们有一个本地声明f state = ...
,我们可以附加一个where
条款,可以访问state
。