Looking through the Haskell Prelude, I see a function const
:
const x _ = x
I can\'t seem to find anything relevant regarding t
Another use is to implement class member functions that have a dummy argument which should not be evaluated (used to resolve ambiguous types). Example that could be in Data.bits:
instance Bits Int where
isSigned = const True
bitSize = const wordSize
...
By using const we explicitly say that we are defining constant values.
Personally I dislike the use of dummy parameters, but if they are used in a class then this is a rather nice way of writing instances.
Say you want to create a list of Nothings
equal to the length of a string. As const
returns its first argument, no matter the second, you can do:
listOfNothings :: String -> [Maybe Char]
listOfNothings = (map . const) Nothing
or, more explicitly:
listOfNothing st = map (const Nothing) st
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.