Infix Functions – Haskell

In Haskell, infix functions are functions that are written between their arguments, rather than before them (prefix functions). This notation is commonly used with operators, such as + or *, but any function that takes two arguments can also be used as an infix function. Infix notation can make code more readable, especially for functions that represent common operations.

Key Points About Infix Functions

  1. Syntax: Infix functions are placed between their two arguments, rather than before them.
    • For example, instead of writing add 2 3, an infix version would be 2 + 3.
  2. Operators as Infix Functions: Most arithmetic and comparison operators, like +, *, &&, and ||, are infix functions by default.
2 + 3    -- Result: 5
True && False  -- Result: False

3. Using Regular Functions as Infix: Any function that takes two arguments can be used as an infix function by enclosing it in backticks (`).

Example:

let add x y = x + y
2 `add` 3    -- Result: 5

4. Defining Custom Infix Operators: You can define custom infix operators using symbolic names (e.g., !+!, ++=, <=>). These custom operators can be used like any other infix function.

Example:

(!+!) :: Int -> Int -> Int
x !+! y = x + y

3 !+! 4    -- Result: 7

5. Associativity and Precedence: Infix functions (especially operators) can have associativity and precedence, which define the order of operations in complex expressions.

  • Associativity determines how operators of the same precedence group, for example, whether a - b - c is grouped as (a - b) - c (left-associative) or a - (b - c) (right-associative).
  • Precedence affects how expressions with different operators are grouped, such as 2 + 3 * 4 being interpreted as 2 + (3 * 4).
-- Define a function
divide :: Int -> Int -> Int
divide x y = x `div` y

-- Use as infix with backticks
10 `divide` 2  -- Result: 5

Examples of Infix Functions

Example 1: Using Backticks with Regular Functions

-- Define a function
divide :: Int -> Int -> Int
divide x y = x `div` y

-- Use as infix with backticks
10 `divide` 2  -- Result: 5

Example 2: Defining a Custom Infix Operator

-- Define a custom infix operator
(<->) :: Int -> Int -> Int
x <-> y = abs (x - y)

-- Use custom infix operator
8 <-> 3  -- Result: 5

In summary, infix functions in Haskell provide a readable way to apply two-argument functions, allowing both built-in and custom functions to be used in infix form for clearer code.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *