I am learning Haskell atm, now I found this function
const const (negate 1) (negate 2) 3
The result of this function is -2. I don't understand why the result is not -2.
const :: a -> b -> a
negate :: Num a => a -> a
So I thought that I can also set the brackets like this: const (const (negate 1) (negate 2)) 3 But now I get -1 as result.
Where is my fault? I do not understand, how this works.
Haskell parsing rules are very simple. If we ignore infix operators (+
, &&
etc.), there is only one rule:
a b c d e
is parsed as(((a b) c) d) e
.
Never, like you assumed, as a (b c d) e
. (Very seldom, this may give the same result by coincidence, but normally it won't even make sense to the type checker.)
So in your example, you have to read it as
( ( (const const) (negate 1) ) (negate 2) ) 3
where const const
simply ignores the (negate 1)
, and yields const
instead. That it turn picks (negate 2)
as its const value, and goes on to ignore 3
.
The brackets need to be set like this:
(((const const) (negate 1)) (negate 2)) 3
Now (const const)
is of type a -> b -> c -> b
and it should be clear why the result is -2
.
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