Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const function in Haskell

Tags:

haskell

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?

like image 755
Rog Matthews Avatar asked Jan 30 '12 10:01

Rog Matthews


People also ask

What does const do Haskell?

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.

What type is const Haskell?

const x is a unary function which evaluates to x for all inputs.

What does id mean in Haskell?

id is just the identity function.

What is flip in Haskell?

Description: it evaluates the function flipping the order of arguments.


2 Answers

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.

like image 146
Chuck Avatar answered Oct 04 '22 11:10

Chuck


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:

  1. 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 )

  2. Prefix operators bind stronger than infix operators

  3. 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 +.

like image 45
snow Avatar answered Oct 04 '22 12:10

snow