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?
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.
Prelude is a module that contains a small set of standard definitions and is included automatically into all Haskell modules.
id is just the identity function.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With