Top Banner
Functional Programming Introduction H. Turgut Uyar 2013-2016
54

Functional Programming - Introduction

Apr 15, 2017

Download

Education

Turgut Uyar
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Functional Programming - Introduction

Functional ProgrammingIntroduction

H. Turgut Uyar

2013-2016

Page 2: Functional Programming - Introduction

License

© 2013-2016 H. Turgut Uyar

You are free to:

Share – copy and redistribute the material in any medium or format

Adapt – remix, transform, and build upon the material

Under the following terms:

Attribution – You must give appropriate credit, provide a link to the license, andindicate if changes were made.

NonCommercial – You may not use the material for commercial purposes.

ShareAlike – If you remix, transform, or build upon the material, you mustdistribute your contributions under the same license as the original.

For more information:https://creativecommons.org/licenses/by-nc-sa/4.0/

Read the full license:

https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode

Page 3: Functional Programming - Introduction

Topics

1 Programming ParadigmsIntroductionImperativeFunctional

2 HaskellExpressionsDefinitionsFunctions

Page 4: Functional Programming - Introduction

Topics

1 Programming ParadigmsIntroductionImperativeFunctional

2 HaskellExpressionsDefinitionsFunctions

Page 5: Functional Programming - Introduction

Paradigms

paradigm: approach to programming

based on a set of principles or theory

different paradigms: different ways of thinking

idioms: patterns for using language features

Page 6: Functional Programming - Introduction

Paradigms

paradigm: approach to programming

based on a set of principles or theory

different paradigms: different ways of thinking

idioms: patterns for using language features

Page 7: Functional Programming - Introduction

Paradigms

imperative: how to solve

procedural, object-oriented

declarative: what to solve

functional, logic

Page 8: Functional Programming - Introduction

Universality

universal: capable of expressing any computation

any language that supports iteration or recursion is universal

Church-Turing thesis:

Any real-world computation can be translatedinto an equivalent computation involving a Turing machine.

It can also be calculated using general recursive functions.

(http://mathworld.wolfram.com/)

Page 9: Functional Programming - Introduction

Universality

universal: capable of expressing any computation

any language that supports iteration or recursion is universal

Church-Turing thesis:

Any real-world computation can be translatedinto an equivalent computation involving a Turing machine.

It can also be calculated using general recursive functions.

(http://mathworld.wolfram.com/)

Page 10: Functional Programming - Introduction

Topics

1 Programming ParadigmsIntroductionImperativeFunctional

2 HaskellExpressionsDefinitionsFunctions

Page 11: Functional Programming - Introduction

Imperative Programming

Alan Turing(1912-1954)

based on the Turing machine

program: sequence of instructionsfor a von Neumann computer

contents of memory constitute state

statements update variables(mutation)

assignment, control structures

natural model of hardware

Page 12: Functional Programming - Introduction

Imperative Programming

Alan Turing(1912-1954)

based on the Turing machine

program: sequence of instructionsfor a von Neumann computer

contents of memory constitute state

statements update variables(mutation)

assignment, control structures

natural model of hardware

Page 13: Functional Programming - Introduction

Imperative Programming Example

greatest common divisor (Python)

def gcd(x, y):r = 0while y > 0:

r = x % yx = yy = r

return x

x y r

9702 945 0945 252 252252 189 189189 63 6363 0 0

~> 63

Page 14: Functional Programming - Introduction

Milestones in Imperative Programming Languages

John Backus(1924-2007)

Fortran (1957)

ALGOL (1960)

C (1972)

Ada (1983)

Java (1995)

Page 15: Functional Programming - Introduction

Topics

1 Programming ParadigmsIntroductionImperativeFunctional

2 HaskellExpressionsDefinitionsFunctions

Page 16: Functional Programming - Introduction

Functional Programming

Alonzo Church(1903-1995)

based on λ-calculus

program: function application

same inputs should producesame output (“pure”)

function modifies context → side effect

avoid mutation

higher-order functions

Page 17: Functional Programming - Introduction

Functional Programming

Alonzo Church(1903-1995)

based on λ-calculus

program: function application

same inputs should producesame output (“pure”)

function modifies context → side effect

avoid mutation

higher-order functions

Page 18: Functional Programming - Introduction

Functional Programming Example

greatest common divisor (Python)

def gcd(x, y):if y == 0:

return xelse:

return gcd(y, x % y)

gcd(9702, 945)~> gcd(945, 252)

~> gcd(252, 189)~> gcd(189, 63)

~> gcd(63, 0)~> 63

~> 63~> 63

~> 63~> 63

Page 19: Functional Programming - Introduction

Side Effects

sources of side effects: global variables

example

factor = 0

def multiples(n):global factorfactor = factor + 1return factor * n

Page 20: Functional Programming - Introduction

Side Effects

sources of side effects: function state, object state

example

class Multiplier:def __init__(self):

self.factor = 0

def multiples(self, n):self.factor = self.factor + 1return self.factor * n

Page 21: Functional Programming - Introduction

Side Effects

sources of side effects: input/output

example

def read_byte(f):return f.read(1)

Page 22: Functional Programming - Introduction

Side Effects

sources of side effects: randomness

example

import random

def get_random(n):return random.randrange(1, n + 1)

Page 23: Functional Programming - Introduction

Problems with Side Effects

harder to reason about programs

harder to test programs

harder to parallelize programs

could we write programs without side effects?

or, at least, could we separate pure and impure parts?

Page 24: Functional Programming - Introduction

Problems with Side Effects

harder to reason about programs

harder to test programs

harder to parallelize programs

could we write programs without side effects?

or, at least, could we separate pure and impure parts?

Page 25: Functional Programming - Introduction

Milestones in Functional Programming Languages

John McCarthy(1927-2011)

Lisp (1957)

ML (1973)

Haskell (1990)

Page 26: Functional Programming - Introduction

Multiple Paradigms

functional languages with object-oriented features

Ocaml, F#, Scala

imperative languages with functional features

Python, Ruby, C#, Java

what makes a language functional or imperative?

higher-order functions

immutable data structures

recommended idioms in functional style

Page 27: Functional Programming - Introduction

Multiple Paradigms

functional languages with object-oriented features

Ocaml, F#, Scala

imperative languages with functional features

Python, Ruby, C#, Java

what makes a language functional or imperative?

higher-order functions

immutable data structures

recommended idioms in functional style

Page 28: Functional Programming - Introduction

Topics

1 Programming ParadigmsIntroductionImperativeFunctional

2 HaskellExpressionsDefinitionsFunctions

Page 29: Functional Programming - Introduction

Expressions and Statements

an expression is evaluated to produce a value

a statement is executed to update a variable

Page 30: Functional Programming - Introduction

Expression and Statement Example

conditional statement (Python)

if x < 0:abs_x = -x

else:abs_x = x

conditional expression (Python)

abs_x = -x if x < 0 else x

conditional expression (Haskell)

abs_x = if x < 0 then -x else x

Page 31: Functional Programming - Introduction

Expression and Statement Example

conditional statement (Python)

if x < 0:abs_x = -x

else:abs_x = x

conditional expression (Python)

abs_x = -x if x < 0 else x

conditional expression (Haskell)

abs_x = if x < 0 then -x else x

Page 32: Functional Programming - Introduction

Expression and Statement Example

conditional statement (Python)

if x < 0:abs_x = -x

else:abs_x = x

conditional expression (Python)

abs_x = -x if x < 0 else x

conditional expression (Haskell)

abs_x = if x < 0 then -x else x

Page 33: Functional Programming - Introduction

Expression and Statement Example

bad:

if age < 18:minor = True

else:minor = False

better:

minor = True if age < 18 else False

much better:

minor = age < 18

Page 34: Functional Programming - Introduction

Expression and Statement Example

bad:

if age < 18:minor = True

else:minor = False

better:

minor = True if age < 18 else False

much better:

minor = age < 18

Page 35: Functional Programming - Introduction

Expression and Statement Example

bad:

if age < 18:minor = True

else:minor = False

better:

minor = True if age < 18 else False

much better:

minor = age < 18

Page 36: Functional Programming - Introduction

Topics

1 Programming ParadigmsIntroductionImperativeFunctional

2 HaskellExpressionsDefinitionsFunctions

Page 37: Functional Programming - Introduction

Definitions

binding: an association between an identifier and an entity

environment: a set of bindings

signature: name, type

definition: name, expression

n :: tn = e

redefining not allowed

Page 38: Functional Programming - Introduction

Definitions

binding: an association between an identifier and an entity

environment: a set of bindings

signature: name, type

definition: name, expression

n :: tn = e

redefining not allowed

Page 39: Functional Programming - Introduction

Definition Examples

-- diameter of the circled :: Floatd = 4.8

-- circumference of the circlec :: Floatc = 3.14159 * d

-- d = 15.62 ~> error: multiple declarations

Page 40: Functional Programming - Introduction

Local Definitions

local definition: used only within expression

n = ewheren1 :: t1n1 = e1

n2 :: t2n2 = e2

...

letn1 :: t1n1 = e1

n2 :: t2n2 = e2

...inn = e

Page 41: Functional Programming - Introduction

Local Definition Example

-- diameter of the circled :: Floatd = 4.8

-- area of the circlea :: Floata = 3.14159 * r * rwherer :: Floatr = d / 2.0

Page 42: Functional Programming - Introduction

Type Inference

Haskell can infer types (more on that later)

we will leave out type declarations for data in local definitions

example

a :: Floata = 3.14159 * r * rwherer = d / 2.0

Page 43: Functional Programming - Introduction

Topics

1 Programming ParadigmsIntroductionImperativeFunctional

2 HaskellExpressionsDefinitionsFunctions

Page 44: Functional Programming - Introduction

Functions

imperative: function body is a block

special construct for sending back the result: return

functional: function body is an expression

Page 45: Functional Programming - Introduction

Function Definitions

function definition:

n :: t1 -> t2 -> ... -> tk -> tn x1 x2 ... xk = e

function application:

n e1 e2 ... ek

Page 46: Functional Programming - Introduction

Function Definitions

function definition:

n :: t1 -> t2 -> ... -> tk -> tn x1 x2 ... xk = e

function application:

n e1 e2 ... ek

Page 47: Functional Programming - Introduction

Function Examples

sqr :: Integer -> Integersqr x = x * x

-- sqr 21 ~> 441-- sqr (2 + 5) ~> 49-- sqr -2 ~> error-- sqr (-2) ~> 4

sumOfSquares :: Integer -> Integer -> IntegersumOfSquares x y = sqr x + sqr y

-- sumOfSquares 3 4 ~> 25-- sumOfSquares 2 (sqr 3) ~> 85

Page 48: Functional Programming - Introduction

Function Example

sumOfCubes :: Integer -> Integer -> IntegersumOfCubes x y = cube x + cube ywherecube :: Integer -> Integercube n = n * n * n

Page 49: Functional Programming - Introduction

Infix - Prefix

functions infix when in backquotes

mod n 2n ‘mod‘ 2

operators prefix when in parentheses

6 * 7(*) 6 7

Page 50: Functional Programming - Introduction

Infix - Prefix

functions infix when in backquotes

mod n 2n ‘mod‘ 2

operators prefix when in parentheses

6 * 7(*) 6 7

Page 51: Functional Programming - Introduction

Guards

writing conditional expressions can become complicated

guards: predicates to check cases

n :: t1 -> t2 -> ... -> tk -> tn x1 x2 ... xk| p1 = e1| p2 = e2...

| otherwise = e

function result is the expression for the first satisfied predicate

Page 52: Functional Programming - Introduction

Guard Example

maximum of three integers

maxThree :: Integer -> Integer -> Integer -> IntegermaxThree x y z| x>=y && x>=z = x| y>=z = y| otherwise = z

Page 53: Functional Programming - Introduction

Errors

errors can be reported using error

doesn’t change the type signature

example: reciprocal (multiplicative inverse)

reciprocal :: Float -> Floatreciprocal x| x == 0 = error "division by zero"| otherwise = 1.0 / x

Page 54: Functional Programming - Introduction

References

Required Reading: ThompsonChapter 1: Introducing functional programming

Chapter 2: Getting started with Haskell and GHCi