在haskell的lambda

问题描述 投票:2回答:1

我正在阅读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

我知道它本身并没有用,但我想知道它是否以及如何成为可能。

haskell syntax where let
1个回答
7
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.