Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

What are these operators doing?

(.) :: (b -> c) -> (a -> b) -> a -> c
(<$>) :: Functor f => (a -> b) -> f a -> f b
(<*>) :: Applicative f => f (a -> b) -> f a -> f b

I don't have any idea when I see the signatures. Perhaps some example with a simple and easy to understand explanation will help me.

like image 464
develhevel Avatar asked Jun 08 '11 14:06

develhevel


People also ask

What does in do in Haskell?

in goes along with let to name one or more local expressions in a pure function. would print "hello world". And you just need one in before you use the names you just defined. And these names definitely don't have to be used as parameters to a function -- they can be just about anything, even functions themselves!

What does a period do in Haskell?

In general terms, where f and g are functions, (f . g) x means the same as f (g x). In other words, the period is used to take the result from the function on the right, feed it as a parameter to the function on the left, and return a new function that represents this computation."

What does apostrophe do in Haskell?

In Haskell it is just another character to distinguish identifiers and the identifier is then called fold prime , but it is commonly used in the same way as it used in mathematics. Save this answer.

What does Fmap do Haskell?

fmap is used to apply a function of type (a -> b) to a value of type f a , where f is a functor, to produce a value of type f b . Note that for any type constructor with more than one parameter (e.g., Either ), only the last type parameter can be modified with fmap (e.g., b in `Either a b`).


1 Answers

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

like image 124
MarcoS Avatar answered Oct 29 '22 17:10

MarcoS