4

I am wondering how this works.

x 9001 = True
x _ = False

g 42 = True
g _ = False

(liftA2 (||) x g) 42 = True

liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
x :: (Eq a, Num a) => a -> Bool
g :: (Eq a, Num a) => a -> Bool

How does the type of x and g (a -> Bool) correspond to what liftA2 expects (f a)?

user1897830
  • 443
  • 1
  • 3
  • 10
  • 1
    Possible duplicate of [functions as applicative functors (Haskell / LYAH)](http://stackoverflow.com/questions/11810889/functions-as-applicative-functors-haskell-lyah) – duplode Oct 16 '16 at 04:31
  • (Hint: remember that `liftA2 f x y = f <$> x <*> y`, and note that the `Applicative` instance involved here is the one for functions.) – duplode Oct 16 '16 at 04:33

1 Answers1

5

Remember that ((->) a) is a Monad (also known as the reader monad), and hence an Applicative too. Taken from the source for base

instance Applicative ((->) a) where
  pure = const
  (<*>) f g x = f x (g x)

Then, liftA2 (||) x g is the function of type (Num a, Eq a) => a -> Bool that checks if either of the results of applying the argument to x and g is True.

Alec
  • 31,829
  • 7
  • 67
  • 114
  • Ok. Thanks for that. Haven't read the reader monad chapter yet. Don't know why they gave it as an example when it hasn't been covered. – user1897830 Oct 16 '16 at 06:34