Functions and Operators

Explore the differences between functions and operators and learn to write your own operators.

After the quite challenging material of the last lessons, we wrap up this section with a few more lightweight lessons on additional syntax, starting with operators.

Functions vs. operators

So far in this course, we have differentiated between functions (like div or mod) and operators (like + or *). The apparent difference between them is that:

  • Functions are used in prefix notation – the function name precedes the arguments (e.g., mod 5 2).
  • Operators are used in infix notation – the operator is between its arguments (e.g., 3 + 5).

Because of the infix notation, operators can only take two arguments, while functions can take any number.

Conceptually, there is no significant difference between operators and binary functions. We can use an operator like a function in prefix notation by enclosing it in parentheses.

Prelude> (+) 3 5
8
Prelude> (/) 8 2
4.0

In fact, we can even do the opposite and use a binary function in infix notation like an operator. All we need to do is enclose the function name in backticks. This is particularly useful for the div and mod function, as it gives them a more natural look and feel.

Prelude> 7 `div` 2
3
Prelude> 7 `mod` 2
1

You can use the following terminal running ghci to try out using operators and functions in both infix and prefix notation.

Get hands-on with 1200+ tech skills courses.