me2
me2

Reputation: 3953

What is the Haskell `(->) a` monad?

At the page http://www.haskell.org/haskellwiki/Pointfree#Tool_support, it talks about the (->) a monad.

What is this monad? The use of symbols makes it hard to google.

Upvotes: 3

Views: 170

Answers (2)

bheklilr
bheklilr

Reputation: 54058

It is the function monad, and it's a bit weird to understand. It's also sometimes called the Reader monad, by the way. I think the best way to illustrate how it works is through an example:

f1 :: Double -> Double
f1 x = 10 * x + x ** 2 + 3 * x ** 3

f2 :: Double -> Double
f2 = do
    x1 <- (10 *)
    x2 <- (** 2)
    x3 <- (** 3)
    return $ x1 + x2 + 3 * x3

If you try out both of these, you'll see that you get the same output from both. So what exactly is going on? When you "extract" a value from a function, you get what can be considered its "return value". I put quotes around it because when you return a value from this monad, the value you return is a function.

For an example like this, the implicit argument to f2 gets passed to each <- as an implicit argument. It can be fairly useful if you have a lot of sub expressions with the same argument. As the Reader monad, it is generally used to supply read-only config values.

Upvotes: 4

rampion
rampion

Reputation: 89053

This is a Reader monad. You can think of it as

type Reader r = (->) r -- Reader r a == (->) r a == r -> a
instance Monad (Reader r) where
  return a = const a            
  m >>= f = \r -> f (m r) r    

And do computations like:

double :: Num r => Reader r r
double = do
  v <- id
  return (2*v)

Upvotes: 4

Related Questions