Functions in Haskell
Functions are central in Haskell. We’ll learn about functions with a few different examples.
module Main where
import System.IO
-- Here's a function that takes two Integers and returns
-- their sum as an Integer.
plus :: Integer -> Integer -> Integer
plus a b = a + b
-- In Haskell, functions are curried by default, so we can
-- easily define a function that takes three parameters.
plusPlus :: Integer -> Integer -> Integer -> Integer
plusPlus a b c = a + b + c
main :: IO ()
main = do
-- Call a function just as you'd expect, with
-- `name args`.
let res = plus 1 2
putStrLn $ "1+2 = " ++ show res
let res = plusPlus 1 2 3
putStrLn $ "1+2+3 = " ++ show res
To run the program:
$ runhaskell functions.hs
1+2 = 3
1+2+3 = 6
In Haskell, functions are first-class citizens and are defined using a very concise syntax. The type signature of a function is optional but recommended for clarity.
Unlike some languages, Haskell doesn’t require explicit return statements. The result of the last expression in a function is automatically returned.
Haskell’s type system is powerful and expressive. The ->
in function types represents function application. For example, Integer -> Integer -> Integer
is a function that takes two Integers and returns an Integer.
Haskell uses currying by default, which means a function that takes multiple arguments is actually a series of functions, each taking a single argument. This allows for partial application, a powerful feature in functional programming.
There are several other features to Haskell functions. One is pattern matching, which we’ll look at in future examples.