Haskell basics – Functions

Note: I’ve writing these Haskell blog posts whilst learning Haskell, so do not take them as expert guidance. I will amend the post(s) as I learn more.

Functions are created using the format

function-name params = function-definition

Note: function names must be camelCase.

So for example, let’s assume we have a Calculator module with the functions, add, subtract, multiply and divide might look like this

module Modules.Calculator where

add a b = a + b
subtract a b = a - b
multiply a b = a * b
divide a b = a / b

Function can be created without type information (as shown above) however it’s considered good practise to specify type annotations for the functions, so for example let’s annotate the add function to say it takes Integer inputs and returns an Integer result

add :: Int -> Int -> Int
add a b = a + b

Now if we try to use floating point numbers with the add function, we’ll get a compile time error. Obviously its more likely we’d want to handle floating point numbers with this function, so let’s change it to

add :: Double -> Double -> Double