Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this function working: const const (negate 1) (negate 2) 3

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.

like image 853
basti12354 Avatar asked Dec 05 '22 03:12

basti12354


2 Answers

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.

like image 85
leftaroundabout Avatar answered May 23 '23 22:05

leftaroundabout


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.

like image 23
felix-eku Avatar answered May 23 '23 23:05

felix-eku