[英]How to use Applicative operators for the Maybe and List Monads in Haskell?
Maybe
和List
是monad,我可以按預期使用bind運算符>>=
,如:
Prelude> (Just 0) >>= (\x -> Just(succ x))
Just 1
但是,如果嘗試使用<$>
applicative運算符,我會收到錯誤:
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
<$>
和<*>
在Control.Applicative
中定義,因此您需要導入它們:
import Control.Applicative ((<$>), (<*>))
<$>
是fmap
的中綴版本,因此,對於您的示例,您需要使用<*>
來提升函數應用程序而不是應用程序:
(Just succ) <*> (Just 0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.