Page 1

Functional Programming (TDA 452/DIT 142)

Page 2

Functional Programming 2016

Thomas Hallgren

(adapted slides from David Sands, Koen Lindström Claessen & John Hughes)

Page 3

Why learn Functional Programming?

Page 4

Why Haskell?

Page 5

How to run Haskell code

GHC (The Glasgow Haskell Compiler)

Page 6

A Haskell Demo

Start GHCi in a terminal window

ghci GHCi, version 8.0.1: :? for help

Page 7

Live Demo

Page 8

Currency converter

Page 9

Testing it in GHCi

Page 10

Writing down properties

Page 11

Automated random testing

Page 12

The problem

It's not the function that is wrong, it's the test!

Page 13

Defining a new equality operator

Page 14

Testing again

Page 15

There is still a problem

Page 16

Function definition by cases and recursion

Page 17

Example: Absolute Value

Compute the absolute value of a number

Page 18


Page 19


Page 20

About Recursion

Page 21

Example: Counting intersections

n non-parellel lines. How many intersections (at most)?

Page 22

The solution

Page 23

Types in Haskell

Page 24

Types in GHCi

Page 25

The type of the power function

Page 26

Specifying type signatures is a good idea!