gpt4 book ai didi

haskell - 如何在 Haskell 中使用 Maybe 和 List Monad 的应用运算符?

转载 作者:行者123 更新时间:2023-12-02 18:33:45 24 4
gpt4 key购买 nike

MaybeList是 monad,我可以使用绑定(bind)运算符 >>=正如预期的那样,如:

Prelude> (Just 0) >>= (\x -> Just(succ x))
Just 1

但是,如果尝试使用 <$>应用运算符,我收到错误:

Prelude> (Just succ) <$> (Just 0)

<interactive>:16:6: Not in scope: ‘<$>’

如何更正我的输入,以便最后一个表达式的计算结果为 Just 1 .

最佳答案

出现错误是因为您没有 <$>不是范围(正如编译器所说)。 <$>运算符由模块 Data.Functor 提供和Control.Applicative 。因此只需将模块加载到 ghci 即可:

:m Control.Applicative

或者如果您不在 ghci

import Control.Applicative

请注意,以 base-4.8 开头(ghc 7.10),<$>包含在 Prelude 中,因此默认导入。

但这并不是您唯一的问题。 <$> ( fmap ) 允许您将函数应用于 Functor/Monad/Applicative 内的某个值。例如

succ <$> Just 0
-- => Just 1
succ <$> Nothing
-- => Nothing
fmap succ (Just 0)
-- => Just 1

但是如果你想应用一个位于 Functor/Monad/Applicative 内部的函数,你需要 <*>

Just succ <*> Just 1
-- => Just 2
Nothing <*> Just 1
-- => Nothing
Just succ <*> Nothing
-- => Nothing

此运算符对于具有多个参数的函数非常有用:

(+) <$> Just 1 <*> Just 2
-- Just (+1) <*> Just 2 (intermediate step)
-- => Just 3

关于haskell - 如何在 Haskell 中使用 Maybe 和 List Monad 的应用运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31852435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com