【问题标题】:Where with lambda in haskell在 haskell 中使用 lambda 的位置
【发布时间】:2019-07-24 08:52:38
【问题描述】:

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

    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 -> ...,我们可以在其上附加一个where 子句,该子句可以访问state

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多