4
votes

I am confused about one particular example of the const function. So the type declaration const :: a -> b->a states that the function accepts two parameters of type a and b and returns a type a. For example:

const 5 3 => 5
const 1 2 => 1

This makes sense based on the declaration. However, I ran into this specific example:

const (1+) 5 3 => 4

This makes me question my understanding of the function declaration. I know this function only takes two parameters because I tried:

const 1 5 3 

Now this reassures to me that it only takes 2 parameters. So how does this work? Is the (1+) not a parameter? If not, what is it?

const (1+) 5 3 => 4
1
Remember that a can be any type and the b gets ignored. A specific case could be (a -> a -> a) -> b -> (a -> a -> a). The b gets ignored and returned is a function a -> a -> a waiting for two new inputs.JohEker
(1+) is a single parameter but it can also accept one parameter which means it's a function. const returns it and it, quite naturally accepst a parameter (the third one, 3 in your example)Redu

1 Answers

11
votes

I know this function only takes two parameters (…)

Every function in Haskell takes one parameter. Indeed, if you write:

 const 5  1

then this is short for:

(const 5) 1

The type signature const :: a -> b -> a is a more compact form of const :: a -> (b -> a).

So const 5 will create a function that ignores the parameter (here 1) and returns the value that it was given 5.

Now for const (1+) 5 3 thus thus means that we wrote:

((const (1+)) 5) 3

const (1+) will thus construct a function that ignores the parameter, and returns (1+), hence const (1+) 5 is (1+). We thus then calculate:

(1+) 3

which is 4.