Search code examples
haskellapplicative

Applicative Functor - Haskell


pure (+) <*> (Just 1) <*> (Just 2)

Is the expansion of above expression is correct?

pure (+)  <*> (Just 1) <*> (Just 2)
= (Just (+)) <*> (Just 1) <*> (Just 2)
= (Just (1+)) <*> (Just 2)
= Just 3

if so then why we can't do just this (Just (+)) <*> (Just 2) ?


Solution

  • I believe you have already answered your question in the comments. So just for the sake of completion...

    (Just (+)) <*> (Just 2) is a partially applied function that the REPL cannot print, giving the error:

    • No instance for (Show (Integer -> Integer)) arising from a use of ‘print’,

    but otherwise it is fine.


    No problem here:

    > :t (Just (+)) <*> (Just 2)

    (Just (+)) <*> (Just 2) :: Num a => Maybe (a -> a).


    Completing the function is fine too:

    > f = (Just (+)) <*> (Just 2)

    > f <*> Just 1

    > Just 3

    Your understanding seems perfectly sound.


    Incidentally, another way of writing this is:

    (+) <$> (Just 1) <*> (Just 2)