need to know what <*> <$> and . do in haskell

I am also learning Haskell, and my recommendation is to have a look into Learn You a Haskell for Great Good!, and more precisely:

  • for (.) read Function composition
  • for <$> and <*> read Applicative functors

In essence:

  • (.) is function composition: if you have g :: a -> b and f :: b -> c then f . g is essentially f(g(x)): first use g on an a to get a b and then use f on that b to get a c

  • <$> takes a function taking an a and returning a b, and a functor that contains an a, and it returns a functor that contains a b. So <$> is the same as fmap :: (a -> b) -> f a -> f b

  • <*> takes a functor that contains a function taking an a and returning a b, and a functor that contains an a, and it returns a functor that contains a b. So <*> kind of extract the function from a functor and applies it to an arguments also inside a functor, and finally returns the result into a functor

Note the explanations that you find in the book chapters are better than my attempt above


Maybe you learn via examples (like I do), so here are some simple ones you can mess around with in GHCI.

(.) - Function Composition 
-- (.) :: (b -> c) -> (a -> b) -> a -> c
> f = (+1)
> g = (*2)
> a = f . g
> a 0
1 -- f( g( 0 ) ) or (0 * 2) + 1
> b = g . f
> b 0
2 -- g( f( 0 ) ) or (0 + 1) * 2


<$> - Functor
-- (<$>) :: Functor f => (a -> b) -> f a -> f b
> a = (*2)
> b = Just 4
> a <$> b
Just 8


<*> - Applicative
-- (<*>) :: Applicative f => f (a -> b) -> f a -> f b
> a = Just (*2)
> b = Just 4
> a <*> b
Just 8

I hope that helps.

Tags:

Haskell