The function const
is defined in Prelude as:
const x _ = x
In GHCi, when I tried
Prelude> const 6 5 -> Gives 6
But when I tried
Prelude> const id 6 5 -> Gives 5
Even after making changes like
Prelude> (const id 6) 5 -> Gives 5
Shouldn't this function give 6
as the output of function id
has type id :: a -> a
which should bind like
Prelude> (const 6) 5 -> Gives 6
Why does function const
behave differently?
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.
const x is a unary function which evaluates to x for all inputs.
id is just the identity function.
Description: it evaluates the function flipping the order of arguments.
You seem to be thinking that this is equivalent to const (id 6) 5
, where id 6
evaluates to 6, but it isn't. Without those parentheses, you're passing the id
function as the first argument to const
. So look at the definition of const
again:
const x _ = x
This means that const id 6 = id
. Therefore, const id 6 5
is equivalent to id 5
, which is indeed 5.
Functions can also be parameters to other functions. id becomes a parameter of const.
What the expression (const id 6) 5 really does is:
(const id 6) 5
(const id _) 5 -- grab the first parameter id
id 5
5
For more detail about what operators really do:
Anything in a pair of brackets would be treated as a whole expression (but it doesn't mean it will be calculated first). For example: (map (1+) ), (\x -> (-) x )
Prefix operators bind stronger than infix operators
The left-most prefix operator in an expression would be treated as a function which grabs parameters (including other prefix operators) in an expression from left to right until facing infix operators or the end of line. For example, if you type map (+) id 3 const + 2 in GHCi, you will get an error that says "The function `map' is applied to four arguments..." because map grabs (+), id, 3 and const as parameters before the infix operator +.
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