Whats "infix" in Haskell?

267 Views Asked by At

I have seen Haskell code like this:

infix 4 ~=
(~=) :: Double -> Double -> Bool
x ~= y = abs (x-y) < epsilon
    where epsilon = 1 / 1000

Despite that I know what this code is doing, I would like to know what infix 4 means.

1

There are 1 best solutions below

3
Noughtmare On

That is a fixity declaration:

A fixity declaration gives the fixity and binding precedence of one or more operators.

In particular the infix part of infix 4 ~= means that the operator ~= is not right or left associative, so x ~= y ~= z is not a valid expression.

And the precedence is 4 which means that it binds tighter than for example &&, so x ~= y && z parses as (x ~= y) && z, but less tight than for example ++, so x ~= y ++ z parses as x ~= (y ++ z) (but that fails to type check). In that respect it is the same as comparison operators like ==, so also x == y ~= z will give a parse error.

Here is a table of the fixities of standard operators (from the Haskell 2010 report linked above):

Precedence Left associative Non-associative Right associative
9 !! .
8 ^ , ^^ , **
7 *, /, ‘div‘, ‘mod‘, ‘rem‘, ‘quot‘
6 +, -
5 :, ++
4 ==, /=, <, <=, >, >=, ‘elem‘, ‘notElem‘
3 &&
2 ||
1 >>, >>=
0 $, $!, ‘seq‘