haskell - Haskell 中 lambda 的位置

标签 haskell syntax where-clause let

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

相关文章:

tsql - 哪里存在 - 所有 - 分组依据?

unit-testing - 对秒差距解析器进行美味的 Hunit 测试?

haskell - 使用 repa 时将 Identity monad 与 mmultP 一起使用有什么问题?

haskell - GHCi 是否不应用默认声明来解决类型歧义?

mysql - 如何将字符添加到字符串中的特定索引

SQL;函数和 where 子句

haskell 。 MongoDB 驱动程序或 Aeson 字符集问题

javascript - JQuery 自动完成功能适用于一个部分,但不适用于另一部分

c++ - 如何使用标志变量为设计用于在数组中搜索通过用户输入提供的字符串的程序产生输出?

powershell - 调用 powershell cmdlet 时参数顺序有多重要?