Maybe
和List
是monad,我可以按预期使用绑定运算符>>=
,如下所示:
Prelude> (Just 0) >>= (\x -> Just(succ x))
Just 1
但是如果尝试使用<$>
applicative运算符,我会收到错误:
Prelude> (Just succ) <$> (Just 0)
<interactive>:16:6: Not in scope: ‘<$>’
如何更正我的输入,以便最后一个表达式的计算结果为Just 1
。
答案 0 :(得分:12)
您出现错误是因为您没有<$>
不是范围(正如编译器所说)。 <$>
运算符由模块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
答案 1 :(得分:9)
<$>
和<*>
在Control.Applicative
中定义,因此您需要导入它们:
import Control.Applicative ((<$>), (<*>))
<$>
是fmap
的中缀版本,因此,对于您的示例,您需要使用<*>
来提升函数应用程序而不是应用程序:
(Just succ) <*> (Just 0)