There are several formats for function definitions: Equations Conditional Equations Patterns ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Equations > flatTax income = 0.25 * income ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Conditional Equations A conditional equation has the form: fun params | guard1 = exp1 | guard2 = exp2 etc | otherwise = exp Example: > tax income > | (income < 0) = error "negative income?" > | (income <= 20000) = 0 > | (income <= 50000) = 0.3 * income > | (income <= 90000) = 0.4 * income > | otherwise = 0.5 * income ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Patterns Parameters can be patterns. In this case a function might be defined by multiple equations. Given a call to a function with argument arg, the interpreter selects the first equation with a parameter that matcches arg. Examples: > isZero 0 = True > isZero _ = False -- _ = wildcard > half 0 = 0 > half n = n `div` 2 > isVowel 'a' = True > isVowel 'e' = True > isVowel 'i' = True > isVowel 'o' = True > isVowel 'u' = True > isVowel _ = False ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Locals We can use a where clause to introduce local constants and functions: > small x > = abs(x) <= delta > where delta = 1.0e-10 > tax2 income > | (income < 0) = error "negative income?" > | (income <= income1) = 0 > | (income <= income2) = rate1 * income > | (income <= income3) = rate2 * income > | otherwise = rate3 * income > where > income1 = 20000 > income2 = 50000 > income3 = 90000 > rate1 = 0.3 > rate2 = 0.4 > rate3 = 0.5 > myTax = let income = 32345 in tax2 income > small2 x > = dist x 0 <= delta > where > delta = 1.0e-10 > dist x y = sqrt(square x + square y) > square x = x * x ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Recursion Selection is achieved by patterns or conditionals. Iteration is achieved by recursion: > fact:: Int->Int > fact n > | n <= 1 = 1 > | otherwise = n * fact(n - 1) > fib:: Int->Int > fib 0 = 0 > fib 1 = 1 > fib n = fib(n - 1) + fib(n - 2) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Offside Rule Haskell uses the offsides rule to determine where a definition ends: A defintion is ended by the first text that appears in the same column or to the left of the same column where the defintion began.