Reputation: 160
Maybe
and List
are monads and I can use the bind operator >>=
as expected, as in:
Prelude> (Just 0) >>= (\x -> Just(succ x))
Just 1
However if try to use the <$>
applicative operator, I get an error:
Prelude> (Just succ) <$> (Just 0)
<interactive>:16:6: Not in scope: ‘<$>’
How to correct my input so that this last expression evaluates to Just 1
.
Upvotes: 2
Views: 184
Reputation: 1056
You error arises because you didn't <$>
is not is scope (just as compiler said). The <$>
operator is provided by module Data.Functor
and Control.Applicative
. So just load the module into ghci:
:m Control.Applicative
or if you are not in ghci
import Control.Applicative
note that starting with base-4.8
(ghc 7.10), <$>
is included in Prelude and thus imported by default.
However that's not your only problem. <$>
(fmap
) allow you to apply the function to some value inside the Functor/Monad/Applicative. For example
succ <$> Just 0
-- => Just 1
succ <$> Nothing
-- => Nothing
fmap succ (Just 0)
-- => Just 1
But if you want to apply a function which is itself inside the Functor/Monad/Applicative you need <*>
Just succ <*> Just 1
-- => Just 2
Nothing <*> Just 1
-- => Nothing
Just succ <*> Nothing
-- => Nothing
This operator is extremely useful for functions with several arguments:
(+) <$> Just 1 <*> Just 2
-- Just (+1) <*> Just 2 (intermediate step)
-- => Just 3
Upvotes: 12
Reputation: 144226
<$>
and <*>
are defined in Control.Applicative
, so you need to import them:
import Control.Applicative ((<$>), (<*>))
<$>
is an infix version of fmap
, so, for your example, you need to use <*>
which lifts function application over an applicative:
(Just succ) <*> (Just 0)
Upvotes: 9