Operators, sections, and fixity

Operators are functions

An operator is a function whose name is made of symbols. It can be used in prefix form with parentheses, and any function can be used in infix form with backticks:

2 + 3 -- 5 (+) 2 3 -- the same call 10 `div` 3 -- 3 div 10 3 -- the same call

Backticks turn a named function into an infix one, which reads better for comparisons and membership tests:

import Data.List (isPrefixOf) 3 `elem` [1,2,3] -- True "cat" `isPrefixOf` "catalog" -- True

The common operators

Six of them cover most code you will read. The last two are the ones beginners postpone, and both are worth learning early:

[1,2] ++ [3,4] -- concatenate two lists 1 : [2,3] -- prepend one element [1,2,3] !! 1 -- index into a list, partial putStrLn $ "hi" -- apply, lowest precedence (negate . abs) 3 -- -3, compose two functions, right to left (+1) <$> Just 1 -- fmap as an operator, Just 2

. is the one to practise. It takes two functions and returns the function that applies the right one first, so f . g reads inside out.

Fixity and backticks

Every operator has a precedence from 0 to 9 and an associativity. :info prints both, and the answer explains why an expression groups the way it does:

ghci> :i (+) type Num :: * -> Constraint class Num a where (+) :: a -> a -> a ... -- Defined in ‘GHC.Internal.Num’ infixl 6 + ghci> :i (:) type List :: * -> * data List a = ... | a : [a] -- Defined in ‘GHC.Types’ infixr 5 :

infixl 6 means left associative at level 6, and infixr 5 means right associative at level 5. That is why 1 : 2 : [] needs no parentheses.

Define your own

Any function with a symbolic name can be an operator, and a fixity declaration decides how it groups. Here is a small one for building ranges of text:

(<.>) :: String -> String -> String a <.> b = a ++ "/" ++ b infixr 6 <.> -- "dev" <.> "haskell" <.> "course" -- "dev/haskell/course"

Resist inventing operators for ordinary functions. A reader parses a named function instantly and an unfamiliar symbol only after a lookup, so symbols are for the cases where infix form genuinely reads better.

The code on this page was run with GHC 9.10.3 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image