Functional Programming with Haskell

Nate Mara, April 30 2015

What is functional programming?

Functional programming concepts

  • First-class functions
  • Higher-order functions
  • Pure functions
  • Recursion

Common functional programming languages

  • Haskell
  • Lisp:
    • Scheme
    • Clojure
    • ...
  • Erlang
  • Ocaml
  • F#

What is a function?

Isn't C functional?

No.

A Function is a relation between a set of inputs and a set of permissible outputs with the property that each input is related to exactly one output.

Implications

  • Running a function twice with the same input will generate the same results
  • Caching
  • IO
  • Mutability

So what is C?

C is PROCEDURAL

In C, you define how to do something

In a functional language, you define how the data is created

Basic Haskell syntax

Functions


                            something x = x + 1
                        

Type signatures


something :: Int -> Int
something x = x + 1
                        

Guards


something :: Int -> Int
something x
    | x > 0 = x + 1
    | otherwise = x
                        

Pattern matching


something :: Int -> Int
something 0 = 1
something x = x
                        

something :: [Int] -> Bool
something [] = True
something x = False
                        

GHCi

Glasgow Haskell Compiler

  1. Write functions in .hs file
  2. Call functions from interactive session

func.hs


isEmpty :: [a] -> Bool
isEmpty [] = True
isEmpty x = False
                        

GHCi


 λ ghci func.hs
GHCi, version 7.6.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( func.hs, interpreted )
Ok, modules loaded: Main.
*Main> isEmpty []
True
*Main> isEmpty [12, 13]
False
                        

First-class functions

Functions as data


> let addOne x = x + 1
> let apply x f = f x

> apply 10 addOne
11
                        

Higher-order functions

Functions that act on other functions


> let addOne x = x + 1
> let myNums = [0, 1, 2, 3, 4, 5]

> map addOne myNums
[1,2,3,4,5,6]
                        

Anonymous functions


> let myNums = [0, 1, 2, 3, 4, 5]

> map (\x -> x * 100) myNums
[0,100,200,300,400,500]
                        

Pure Functions

Functions that eschew side-effects

  • Read/write a file
  • Update a database
  • Print to the user
  • Read/write on a network connection

Recursion


max :: (Ord a) => [a] -> a
max [] = error
max [x] = x
max (x:xs)
    | x > maxTail = x
    | otherwise = maxTail
    where maxTail = max xs
                        

What does this do?


something :: (Ord a) => [a] -> [a]
something [] = []
somthing (x:xs) =
    let f = something [a | a <- xs, a <= x]
        b = something [a | a <- xs, a > x]
    in f ++ [x] ++ b
                        

Further information