Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of 'const' in the Haskell Prelude?

Tags:

haskell

Looking through the Haskell Prelude, I see a function const:

const x _ = x 

I can't seem to find anything relevant regarding this function.

What's the point? Can anyone give an example of where this function might be used?

like image 405
stusmith Avatar asked Sep 13 '11 13:09

stusmith


People also ask

What does const do Haskell?

const takes two arguments, discards the second and returns the first. Seen as a function of one argument, a -> (b -> a) , it returns a constant function, which always returns the same value no matter what argument it is given.

What is the prelude in Haskell?

Prelude is a module that contains a small set of standard definitions and is included automatically into all Haskell modules.

What does id mean in Haskell?

id is just the identity function.


2 Answers

It's useful for passing to higher-order functions when you don't need all their flexibility. For example, the monadic sequence operator >> can be defined in terms of the monadic bind operator as

x >> y = x >>= const y 

It's somewhat neater than using a lambda

x >> y = x >>= \_ -> y 

and you can even use it point-free

(>>) = (. const) . (>>=) 

although I don't particularly recommend that in this case.

like image 199
hammar Avatar answered Sep 18 '22 15:09

hammar


To add to hammar's excellent direct answer: humble functions like const and id are really useful as a higher order function for the same reason that they are fundamental in the SKI combinator calculus.

Not that I think haskell's prelude functions were modeled consciously after that formal system or anything. It's just that creating rich abstractions in haskell is very easy, so you often see these types of theoretical things emerge as practically useful.

Shameless plug, but I blogged about how the Applicative instance for (->) are actually the S and K combinators here, if that's the kind of thing you're into.

like image 21
jberryman Avatar answered Sep 20 '22 15:09

jberryman