Many times I tried to understand Functor and Monad in Haskell, but I failed. This time when I reached at LYAH's Applicative Functor, and thought I understood Applicative typeclasses
, but I had some doubt about Applicative instance implementation for Maybe:
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> something = fmap f something
For the last line of above snippet, my understanding as follows:
(1) Just f
is appropriated to f (a->b)
in (<*>) :: f (a -> b) -> f a -> f b
of class definition of Applicative, and f
is appropriated to (a->b)
(2) something
is appropriated to f a
.
my question is from (2), why there is not written like Just something
or the like?
In the Functor instance implementation for Maybe, there is fmap f (Just x) = Just (f x)
and Just x
is appropriated to f a
of fmap :: (a -> b) -> f a -> f b
.
for verifying my understanding, I changed something
into Just something
:
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> (Just something) = fmap f (Just something)
under gchi, I tried
Just (+3) <*> Just 9
and got the same result Just 12
, but when I tried
Just (++"hahah") <*> Nothing`
I got the error
*** Exception: Functor.hs:(88,3)-(89,60): Non-exhaustive patterns in function <*>
I don't know why or what things I miss?
(Just f) <*> something
and(Just f) <*> (Just something)
are not equivalent;something
is just a variable and matches anything, including the constructorNothing
, whileJust something
will not match nothing. Your idea will work correctly if you have also haveJust _ <*> Nothing = Nothing
. However, this is 3 lines, and programmers are lazy, so why write something in 3 lines that can be written in 2? – user2407038something
includedJust somthing
? – abelard2008_
in line 2 can be replaced bysomething
(of course I have tested it usingsomething
in line 2)? the reason for using_
is laziness? – abelard2008something
will matchJust x
._
is equally as lazy as just a variable. SoNothing <*> x = Nothing
would behave exactly the same way. The purpose of_
is to communicate to readers of your program that that parameter is not used. – user2407038