8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
1/42
Functional ProgrammingPart I: Introduction
CT006-3-3: Advanced Programming
Language Concepts
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
2/42
Module Code and Module Title Title of Slides
Topic and Structure of the Lesson
1. Functions
2. Functional Programming Notation and Types
3. Pattern Matching and Recursion
4. Tuples and comparison to lists
5. Comparison of FP to other paradigms
6. Pros/Cons of FP
7. Exercises
- Quick Quizzes
- Sample exercises
Slide 2 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
3/42
Module Code and Module Title Title of Slides
Learning Outcomes
Functional programming basics
Compare functional programming to other
programming paradigms with regard tofundamental characteristics
Give the advantages and disadvantages of
functional programming
Slide 3 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
4/42
Module Code and Module Title Title of Slides
Key Terms
1. Function
2. Value
3. Expression
4. Operator5. Definition
6. Function Definition
7. Functional Program
8. Pattern Matching9. Recursion
10. Tuple
11. Side effect
Slide 4 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
5/42
Module Code and Module Title Title of Slides
Functions
A function is a way of computing a result
from a list of arguments.
f(x) = sin x / cos x
button(mouse click) = close window
A functional program computes its output
as a function of its input
Slide 5 (of 42)
x is the
argument
(angle)
A function
that closes awindow
based on a
button click
Source:
http://www.cs.chalmers.se/Cs/Grundutb/Kurser/d1pt/d1pta/external.html#links
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
6/42
Module Code and Module Title Title of Slides
Values and Expressions
A value, or literal, is a piece of data:
2, 4, 3.14159, Tarun, a, etc.
An expressioncomputes a value:
2 + 2, 2*pi*r
Expressions combine values using
functions and operators
Slide 6 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
7/42Module Code and Module Title Title of Slides
Operators and Operations
Operators combine values into separate
results:
b^24*a*c Operations such as multiplication,
subtraction, etc. can be unary or binary,
using operators to achieve a result
-5 (negating a value is a unary operation)
5 + 2 (adding two values is a binary operation)
Slide 7 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
8/42Module Code and Module Title Title of Slides
Definitions and Types
A definition gives a name to a value
Slide 8 (of 42)
area :: Int
area = 41 * 37
Types* specify what
kind of value this is.
* Basic Types: Int ,Float, Char, Bool
Structured Types: lists, tuples, functions, classes (we will discuss classes and
generics more in Week 7)
An expression says how
the value is computed.
Names start with a
small letter, and are
made up of
letters and digits.
Haskell
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
9/42Module Code and Module Title Title of Slides
Function Definitions
A function definitionspecifies how the result is computed
from the arguments.
Slide 9 (of 42)
area :: Int -> Int -> Int
area l b = l*b
Function types specify the
types of the arguments
and the result.
The arguments
are given names,
after the function
name.
The body specifies how
the result is computed.
Cf. area(l,b) = l*b
arg arg result
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
10/42Module Code and Module Title Title of Slides
Function Notation
Slide 10 (of 42)
Function arguments need notbe enclosed in brackets!
Example: average :: Float -> Float -> Float
average x y = (x + y) / 2
Calls: average 2 3 2.5
average (2+2) (3*3) 6.5
Brackets are for grouping only!
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
11/42Module Code and Module Title Title of Slides
Functional Programming
Slide 11 (of 42)
A functional programconsists mostly of function
definitions.
Simple functions are used to define more complex ones,which are used to define still more complex ones, and so
on.
Finally, we define a function to compute the output of theentire program from its inputs.
If you can write function definitions, you can write
functional programs!
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
12/42Module Code and Module Title Title of Slides
Types
From mathematics, were used to
functions whose arguments and results
are numbers. In programs, we usually
work with much richer types.
Some types are built in to programming
languages (basic types usually), whereas
others are defined by programmers
(through structs, classes, etc.)
Slide 12 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
13/42Module Code and Module Title Title of Slides
Integer Type
Slide 13 (of 42)
1, 2, 3, 4 :: Int
Whole numbers
(between -2^31
and 2^31-1)
[32-bit]
2+3 5
2*3 6
2^3 8
div 7 2 3
mod 7 2 1
Some operations:
integer division!
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
14/42
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
15/42Module Code and Module Title Title of Slides
List Type
Slide 15 (of 42)
[1,2,3] :: [Int]A list of integers.
A list of values
enclosed in
square brackets.
Some operations:
[1,2,3] ++[4,5] [1,2,3,4,5]
head [1,2,3] 1
last [1,2,3] 3
concatenates
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
16/42Module Code and Module Title Title of Slides
Quick Review and Exercise
How would you add 4 to the end of the list [1,2,3]?
Define a function that takes in two floats and adds them
up
What are the basic and structured types available in
Haskell?
What are brackets used for in function notation?
Slide 16 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
17/42Module Code and Module Title Title of Slides
String Type
Slide 17 (of 42)
Hello! :: StringAny characters
enclosed in
double quotes.
The type of
a piece of text.
Some operations:
Hello ++ World Hello World
show (2+2) 4
Is 2+2 equal to 4?
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
18/42
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
19/42
Module Code and Module Title Title of Slides
Quick Quiz
Slide 19 (of 42)
If myfile contains Hello!,
is readFile myfile equal to Hello!?
NO! This is a commandto read a file.
This is a constant
piece of text.
The result of a function depends only on its arguments;
Hello! cannot be computed from myfile.
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
20/42
Module Code and Module Title Title of Slides
Pattern Matching and Recursion
Slide 20 (of 42)
Problem: define fac :: Int -> Int
fac n = 1 * 2 * * n
What if we already know the value of fac (n-1)?
Then fac n = 1 * 2 * * (n-1) * n
= fac (n-1) * n
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
21/42
Module Code and Module Title Title of Slides
Pattern Matching and Recursion
Slide 21 (of 42)
n fac n
0 1
1 1
2 2
3 6
4 24
...
Must start somewhere:
we know that fac 0 = 1.
So fac 1 = 1 * 1.
So fac 2 = 1 * 2.
So fac 3 = 2 * 3.
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
22/42
Module Code and Module Title Title of Slides
Pattern Matching and Recursion
Slide 22 (of 42)
fac :: Int -> Int
fac 0 = 1
fac n | n > 0 = fac (n-1) * n
Base case.
Pattern matching on 0.
Recursive case.
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
23/42
Module Code and Module Title Title of Slides
Pattern Matching and Recursion
Slide 23 (of 42)
fac :: Int -> Int
fac 0 = 1
fac n | n > 0 = fac (n-1) * n
fac 4 ?? 4 == 0 False
?? 4 > 0 True
fac (4-1) * 4
fac 3 * 4
fac 2 * 3 * 4
fac 1 * 2 * 3 * 4
fac 0 * 1 * 2 * 3 * 4
1 * 1 * 2 * 3 * 4
24
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
24/42
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
25/42
Module Code and Module Title Title of Slides
Quick Review of Recursion
Slide 25 (of 42)
Recursion lets us decompose a problem into smaller
subproblems of the same kind -- a powerful problem
solving tool in any programming language!
A more general problem may be easier to solve
recursively than a `simpler one, because the recursive
calls can do more.
To ensure termination, define a `problem size which
must be greater than zero in the recursive cases, and
decreases by at least one in each recursive call.
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
26/42
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
27/42
Module Code and Module Title Title of Slides
Tuple Types
Slide 27 (of 42)
A tuple typespecifies the type of each component.
Examples:
(1,2) :: (Int, Int)
(1.5, 2.25) :: (Float, Float)
(Dagens Lunch, 55) :: (String, Int)
() :: ()
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
28/42
Module Code and Module Title Title of Slides
Type Definitions
Slide 28 (of 42)
We can give names to types with a type definition:
typePurchase = (String, Int)
Now Purchase and (String, Int) are interchangeable:
dagens :: Purchase
dagens = (Dagens Lunch, 55)
All types start with a capital letter.
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
29/42
Module Code and Module Title Title of Slides
Pattern Matching with Tuples
Slide 29 (of 42)
Functions on tuples can be defined bypattern matching:
name :: Purchase -> String
name (s, i) = s
price :: Purchase -> Int
price (s, i) = i
Apatternwhich must match
the actual argument.
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
30/42
Module Code and Module Title Title of Slides
Tuples vs. Lists
Slide 30 (of 42)
A tuple consists of afixed
number of components, of
varioustypes.
Useful, but not much to
know.
A list consists of any number
of elements, all of thesame
type.
Ubiquitous! Supported by a
rich set of standard functions
and constructions.
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
31/42
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
32/42
Module Code and Module Title Title of Slides
Using Lists
Slide 32 (of 42)
We often do the same thing to every element of a list:
Example:
doubles :: [Int] -> [Int]
doubles xs = [2 * x | x
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
33/42
Module Code and Module Title Title of Slides
Summing Squares in a List
Slide 33 (of 42)
n
[1, 2, 3, , n]
[1, 4, 9, , n^2]
1 + 4 + 9 + + n^2
sumsq :: Int -> Int
sumsq n = sum [i^2 | i
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
34/42
Module Code and Module Title Title of Slides
Filtering Elements in a List
Slide 34 (of 42)
A list function can include a conditionwhich elements must
satisfy.
Example:
factors :: Int -> [Int]
factors n = [i | i
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
35/42
Module Code and Module Title Title of Slides
Lists vs. Recursion
Slide 35 (of 42)
Haskells powerful list constructions often offer a simpler
alternative to using recursion.
But not always! Recursion is a powerful and general tool --
therefore harder to use than special purpose tools, when they
are applicable.
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
36/42
Module Code and Module Title Title of Slides
Comparison of FP with other
language paradigms
Functional programming differs from imperative
and logic programming in several ways:
Avoids side effects, which in other paradigms is used forstate and I/O (Pure functional programming disallows
them altogether). This allows for referentialtransparency.
Higher order functions are rarely used in older imperative
programming; whereas a traditional imperative programmight use a loop to traverse a list, a functional programwould use a higher order function.
Slide 36 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
37/42
Module Code and Module Title Title of Slides
Comparison of FP with other
language paradigms
Simulating state Tasks like maintaining a bank account balance and accepting
user input are accomplished through the use of monads (inHaskell), which are derived from category theory
Efficiency Functional programming languages have automatic memory
management with garbage collection, in contrast to olderimperative languages like C and Pascal.
Coding style Imperative programs emphasize a series of steps taken by a
program, while functional programs emphasize the compositionand arrangement of functions
Slide 37 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
38/42
Module Code and Module Title Title of Slides
Advantages of using FP
Unit Testing Since every symbol in FP is final (non-mutable), no
function can ever cause side effects (no unexpectedchanges in state). You can test every function in yourprogram only worrying about its arguments! In animperative language, checking a return value is notsufficientit may modify external state.
Debugging A bug in a functional program does not depend on
unrelated code paths that were executed before it. Awrong return value is alwayswrong (idempotence),whereas in an imperative language, a wrong valuemay crop up intermittently.
Slide 38 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
39/42
Module Code and Module Title Title of Slides
Advantages of using FP
Concurrency In FP, you dont have to worry about deadlocks or
race conditions. This makes FP ideal for massivelyconcurrent applications, like telecommunicationswitches (Ericsson developed Erlang for just thispurpose!)
Hot Code Deployment Functional programming allows updating code without
stopping any part of a system. Erlang engineers have
been doing this for years!
Machine-assisted Proofs and Optimizations Automation of code checking for correctness and
optimization strategies are possible with FP.
Slide 39 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
40/42
Module Code and Module Title Title of Slides
Disadvantages of FP
Most of the criticism leveled at functional
programming has to do with difficulty in learning
and lazy evaluation
Learning curve: functional programming is moremathematically-oriented, and may thus present a
challenge to imperative programmers used to that
paradigm
Lazy evaluation, a feature supported in most FPlanguages, can complicate I/O and debugging.
Execution speed of Haskell and some other FP
languages has also stymied adoption.
Slide 40 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
41/42
Module Code and Module Title Title of Slides
Q & A
Any Questions?
Slide 41 (of 42)
8/13/2019 CT006!3!3 ADPLC 02 FunctionalProgramming Part 1
42/42
Next Session
Fundamental functional programming
characteristics
Higher-order functions
Pure functions and referential transparency
Functional composition
Haskell Examples
Simple exercises
Top Related