Search code examples
haskelllazy-evaluationoperator-precedence

What order would Haskell evaluate 2 operands of the same precedence?


For a function that uses the same operand, e.g. + or * more than once, how will it evaluate it?

For example, in the following code:

prodOfThree :: Int -> Int -> Int
prodOfThree a b c = a*b*c

How would the following be evaluated?

prodOfThree (2+3) 4 2

This is as far as I've got:

=> (2 + 3) * 4 * 2
=> 5 * 4 * 2

And then I am unsure of whether it would multiply 5*4 first, 4*2 first or 5*4*2 all at once.


Solution

  • You can ask for an operator's infixity using ghci:

    >>> :info (*)
    class Num a where
      ...
      (*) :: a -> a -> a
      ...
            -- Defined in `GHC.Num'
    infixl 7 *
    

    Or you can look it up on Hackage. A good way to search Hackage is with Hoogle or Hayoo.

    Because * has infixity infixl 7 this means it is left-associative and has precedence 7. Therefore, a * b * c is (a * b) * c.

    A more interesting example is an operator that does not have the mathematical property of associativity such as - (not to be confused with infixity, which it does have). The infixity is infixl 6 and therefore a - b - c is (a - b) - c.

    An example of a right-associative operator is ::

    >>> :info (:)
    data [] a = ... | a : [a]       -- Defined in `GHC.Types'
    infixr 5 :
    

    So a : b : c is a : (b : c). Note that if it was left-associative then a : b : c would (probably) be a type error!