Haskell Functions
Functions are the heart of Haskell. Defining one looks like writing an equation, and calling one needs no parentheses or commas: you simply write the function name followed by its arguments, separated by spaces.
Defining and calling functions
square :: Int -> Int
square x = x * x
area :: Double -> Double -> Double
area width height = width * height
greet :: String -> String
greet name = "Hello, " ++ name ++ "!"
main :: IO ()
main = do
print (square 9)
print (area 3.5 2)
putStrLn (greet "Ada")81
7.0
Hello, Ada!
Read square x = x * x as "square of x is x times x". The left side names the function and its parameters; the right side is the result. There is no return keyword: the body is the value.
| Other languages | Haskell |
|---|---|
square(9) |
square 9 |
area(3.5, 2) |
area 3.5 2 |
square(square(3)) |
square (square 3) |
f(x) + g(y) |
f x + g y |
Function application binds tightest
Function application has higher precedence than every operator. That is why f x + g y means (f x) + (g y), and why you need parentheses when an argument is itself an expression:
square :: Int -> Int
square x = x * x
main :: IO ()
main = do
print (square 3 + 1) -- (square 3) + 1
print (square (3 + 1)) -- square 4
print (square (square 2)) -- nested calls need parentheses10
16
16
Forgetting the parentheses in square square 2 is a classic beginner error: it passes two arguments (square and 2) to square, and GHC complains.
Functions calling functions
Larger functions are built from smaller ones. Here a shopping total is assembled from small, testable pieces:
priceWithTax :: Double -> Double
priceWithTax price = price * 1.2
lineTotal :: Double -> Int -> Double
lineTotal unitPrice quantity = unitPrice * fromIntegral quantity
orderTotal :: Double
orderTotal = priceWithTax (lineTotal 2.5 4 + lineTotal 10 1)
main :: IO ()
main = do
print (lineTotal 2.5 4)
print orderTotal10.0
24.0
orderTotal has no parameters: it is a constant, a "function" of zero arguments. In Haskell a name bound to a value and a function defined with = are the same kind of thing.
Infix and prefix
Any two-argument function can be used between its arguments with backticks, and you can define your own operators out of symbols:
percentOf :: Double -> Double -> Double
percentOf p total = total * p / 100
-- A custom operator: "approximately equal"
infix 4 ~= -- same precedence as == (see below)
(~=) :: Double -> Double -> Bool
a ~= b = abs (a - b) < 0.001
main :: IO ()
main = do
print (percentOf 15 80)
print (15 `percentOf` 80) -- same call, infix style
print (0.1 + 0.2 ~= 0.3)
print ((~=) 1.0 1.5) -- an operator used as a prefix function12.0
12.0
True
False
The infix 4 ~= line is a fixity declaration. Without it a new operator binds as tightly as possible (infixl 9), so 0.1 + 0.2 ~= 0.3 would be read as 0.1 + (0.2 ~= 0.3) and fail to type-check. Level 4 is the level of == and <, below + (level 6).
Naming rules
- Function and variable names start with a lowercase letter or
_:total,parseLine,x'. A trailing apostrophe (pronounced "prime") is allowed and often marks a slightly modified version, such asfoldl'. - Names starting with an uppercase letter are reserved for types and constructors (
Int,True,Just). - Operators are made of symbols like
+ * < > = ! ~ . |. - Haskell code uses
camelCase.
Local definitions
A function can define helpers that only it can see, with where (after the body) or let … in (before it). You will study both in detail later; here is a first taste:
bmi :: Double -> Double -> String
bmi weightKg heightM = category ++ " (" ++ show rounded ++ ")"
where
value = weightKg / heightM ^ 2
rounded = fromIntegral (round (value * 10)) / 10
category = if value < 25 then "normal" else "above normal"
main :: IO ()
main = do
putStrLn (bmi 70 1.75)
putStrLn (bmi 90 1.70)normal (22.9)
above normal (31.1)
Tip: Keep functions short. If a body grows past a few lines, give the parts names in a
whereblock. Small named pieces are the Haskell way to make code readable.
Test yourself
How do you call a function area with arguments 3 and 4?
area(3, 4)area 3 4area(3)(4)onlyarea [3, 4]
What does square 2 + 3 evaluate to, with square x = x * x?
- 25
- 7
- 10
- A type error
Which of these is a valid function name?
Totaltotal'2totaltotal-sum