Sie sind auf Seite 1von 42

CT006-3-3: Advanced Programming Language Concepts

Functional Programming
Part I: Introduction

Topic and Structure of the Lesson


1. 2. 3. 4. 5. 6. 7. Functions Functional Programming Notation and Types Pattern Matching and Recursion Tuples and comparison to lists Comparison of FP to other paradigms Pros/Cons of FP Exercises
- Quick Quizzes - Sample exercises
Module Code and Module Title Title of Slides Slide 2 (of 42)

Learning Outcomes
Functional programming basics Compare functional programming to other programming paradigms with regard to fundamental characteristics Give the advantages and disadvantages of functional programming

Module Code and Module Title

Title of Slides

Slide 3 (of 42)

Key Terms
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
Module Code and Module Title

Function Value Expression Operator Definition Function Definition Functional Program Pattern Matching Recursion Tuple Side effect
Title of Slides Slide 4 (of 42)

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
x is the argument (angle) A function that closes a window based on a button click

A functional program computes its output as a function of its input


Source: http://www.cs.chalmers.se/Cs/Grundutb/Kurser/d1pt/d1pta/external.html#links
Module Code and Module Title Title of Slides Slide 5 (of 42)

Values and Expressions


A value, or literal, is a piece of data:
2, 4, 3.14159, Tarun, a, etc.

An expression computes a value:


2 + 2, 2*pi*r

Expressions combine values using functions and operators


Module Code and Module Title Title of Slides Slide 6 (of 42)

Operators and Operations


Operators combine values into separate results:
b^2 4*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)
Module Code and Module Title Title of Slides Slide 7 (of 42)

Definitions and Types


A definition gives a name to a value
Types* specify what kind of value this is.

Haskell

Names start with a small letter, and are made up of letters and digits.

area :: Int

area = 41 * 37
An expression says how the value is computed.

* Basic Types: Int ,Float, Char, Bool Structured Types: lists, tuples, functions, classes (we will discuss classes and generics more in Week 7)
Module Code and Module Title Title of Slides Slide 8 (of 42)

Function Definitions
A function definition specifies how the result is computed from the arguments.
arg

arg

result

area :: Int -> Int -> Int area l b = l*b

Function types specify the types of the arguments and the result. The body specifies how the result is computed.

The arguments are given names, after the function name.


Module Code and Module Title

Cf. area(l,b) = l*b


Title of Slides Slide 9 (of 42)

Function Notation

Function arguments need not be 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!


Module Code and Module Title Title of Slides Slide 10 (of 42)

Functional Programming
A functional program consists 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 the entire program from its inputs. If you can write function definitions, you can write functional programs!
Module Code and Module Title Title of Slides Slide 11 (of 42)

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.)
Module Code and Module Title Title of Slides Slide 12 (of 42)

Integer Type
Whole numbers (between -2^31 and 2^31-1) [32-bit]

1, 2, 3, 4

:: Int

Some operations:
2+3 2*3 5 6 div 7 2 mod 7 2 3 1

2^3

8
integer division!

Module Code and Module Title

Title of Slides

Slide 13 (of 42)

Real Number Type


Real numbers (with about 6 significant figures).

1.5, 0.425, 3.14159 :: Float

Some operations:
2.5 + 1.5 3 - 1.2 1.4142^2 4.0 1.8 1.99996

1/3

0.333333

sin (pi/4)

0.707107

Module Code and Module Title

Title of Slides

Slide 14 (of 42)

List Type
A list of values enclosed in square brackets.

A list of integers. [1,2,3] :: [Int]

Some operations: [1,2,3] ++[4,5]


concatenates

[1,2,3,4,5]

head [1,2,3]
last [1,2,3]
Module Code and Module Title Title of Slides

1
3
Slide 15 (of 42)

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?

Module Code and Module Title

Title of Slides

Slide 16 (of 42)

String Type

Any characters enclosed in double quotes. Some operations:

Hello! :: String

The type of a piece of text.

Hello ++ World

Hello World

show (2+2)

Is 2+2 equal to 4?
Module Code and Module Title Title of Slides Slide 17 (of 42)

Command Type
A command to write Hello! to myfile. The type of a command which produces no value.

writeFile myfile Hello! :: IO () readFile myfile :: IO String

The type of a command which produces a String.


Module Code and Module Title Title of Slides Slide 18 (of 42)

Quick Quiz
If myfile contains Hello!,
is readFile myfile equal to Hello!?

NO!

This is a command to 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.

Module Code and Module Title

Title of Slides

Slide 19 (of 42)

Pattern Matching and Recursion


Problem: define fac :: Int -> Int fac n = 1 * 2 * * n

What if we already know the value of fac (n-1)? = 1 * 2 * * (n-1) * n = fac (n-1) * n

Then fac n

Module Code and Module Title

Title of Slides

Slide 20 (of 42)

Pattern Matching and Recursion


Must start somewhere: we know that fac 0 = 1.
So fac 1 = 1 * 1. So fac 2 = 1 * 2. So fac 3 = 2 * 3.

n 0 1 2 3 4 ...

fac n 1 1 2 6 24

Module Code and Module Title

Title of Slides

Slide 21 (of 42)

Pattern Matching and Recursion

fac :: Int -> Int fac 0 = 1

Base case. Pattern matching on 0. Recursive case.

fac n | n > 0 = fac (n-1) * n

Module Code and Module Title

Title of Slides

Slide 22 (of 42)

Pattern Matching and Recursion


fac :: Int -> Int

fac 0 = 1
fac n | n > 0 = fac (n-1) * n

fac 4

?? 4 == 0 ?? 4 > 0

False True

fac 2 * 3 * 4 fac 1 * 2 * 3 * 4

fac (4-1) * 4
fac 3 * 4

fac 0 * 1 * 2 * 3 * 4
1*1*2*3*4 24

Module Code and Module Title

Title of Slides

Slide 23 (of 42)

Quick Quiz
Define a function power so that power x n == x * x * * x n times

(Of course, power x n == x^n, but you should define power without using ^).
power x 0 = 1 Dont forget the base case!

power x n | n > 0 = power x (n-1) * x

Since this equals (x * x * * x) * x


n-1 times

Module Code and Module Title

Title of Slides

Slide 24 (of 42)

Quick Review of Recursion


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.
Module Code and Module Title Title of Slides Slide 25 (of 42)

Tuples
A tuple is a value made up of several other values, namely its components.
Examples: A point in the plane (x,y) A point in space (x,y,z)

Round brackets and commas.

A purchase
The null tuple
Module Code and Module Title

(Dagens Lunch, 55)


()
Title of Slides Slide 26 (of 42)

Tuple Types
A tuple type specifies the type of each component.

Examples:

(1,2) :: (Int, Int)


(1.5, 2.25) :: (Float, Float) (Dagens Lunch, 55) :: (String, Int) () :: ()

Module Code and Module Title

Title of Slides

Slide 27 (of 42)

Type Definitions
We can give names to types with a type definition:

type Purchase = (String, Int) All types start with a capital letter. Now Purchase and (String, Int) are interchangeable: dagens :: Purchase dagens = (Dagens Lunch, 55)

Module Code and Module Title

Title of Slides

Slide 28 (of 42)

Pattern Matching with Tuples


Functions on tuples can be defined by pattern matching:

name :: Purchase -> String

name (s, i) = s
A pattern which must match the actual argument.

price :: Purchase -> Int price (s, i) = i

Module Code and Module Title

Title of Slides

Slide 29 (of 42)

Tuples vs. Lists


A tuple consists of a fixed number of components, of various types. A list consists of any number of elements, all of the same type.

Useful, but not much to know.

Ubiquitous! Supported by a rich set of standard functions and constructions.

Module Code and Module Title

Title of Slides

Slide 30 (of 42)

Using Lists
We often need to count:
[1..10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [1,3..10] = [1, 3, 5, 7, 9] Example: fac :: Int -> Int

fac n = product [1..n]


Standard function to multiply together list elements.
Module Code and Module Title Title of Slides Slide 31 (of 42)

Using Lists
We often do the same thing to every element of a list:

Example:

doubles :: [Int] -> [Int]


doubles xs = [2 * x | x <- xs]

For each element x of xs...

Add 2*x to the list produced.


doubles [1..3]
Module Code and Module Title

[2, 4, 6]
Title of Slides Slide 32 (of 42)

Summing Squares in a List


n
[1, 2, 3, , n] [1, 4, 9, , n^2] 1 + 4 + 9 + + n^2 sumsq :: Int -> Int sumsq n = sum [i^2 | i <- [1..n]] Add up the elements of a list.
Module Code and Module Title Title of Slides Slide 33 (of 42)

Filtering Elements in a List


A list function can include a condition which elements must satisfy. Include only those i which pass this test.

Example:
factors :: Int -> [Int]

factors n = [i | i <- [2..n], n `mod` i == 0]

factors 12
Module Code and Module Title

[2, 3, 4, 6, 12]
Title of Slides Slide 34 (of 42)

Lists vs. Recursion

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.

Module Code and Module Title

Title of Slides

Slide 35 (of 42)

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 for state and I/O (Pure functional programming disallows them altogether). This allows for referential transparency . Higher order functions are rarely used in older imperative programming; whereas a traditional imperative program might use a loop to traverse a list, a functional program would use a higher order function.

Module Code and Module Title

Title of Slides

Slide 36 (of 42)

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 (in Haskell), which are derived from category theory

Efficiency
Functional programming languages have automatic memory management with garbage collection, in contrast to older imperative languages like C and Pascal.

Coding style
Imperative programs emphasize a series of steps taken by a program, while functional programs emphasize the composition and arrangement of functions
Module Code and Module Title Title of Slides Slide 37 (of 42)

Advantages of using FP
Unit Testing
Since every symbol in FP is final (non-mutable), no function can ever cause side effects (no unexpected changes in state). You can test every function in your program only worrying about its arguments! In an imperative language, checking a return value is not sufficient it may modify external state.

Debugging
A bug in a functional program does not depend on unrelated code paths that were executed before it. A wrong return value is always wrong (idempotence), whereas in an imperative language, a wrong value may crop up intermittently.
Module Code and Module Title Title of Slides Slide 38 (of 42)

Advantages of using FP
Concurrency
In FP, you dont have to worry about deadlocks or race conditions. This makes FP ideal for massively concurrent applications, like telecommunication switches (Ericsson developed Erlang for just this purpose!)

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.
Module Code and Module Title Title of Slides Slide 39 (of 42)

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 more mathematically-oriented, and may thus present a challenge to imperative programmers used to that paradigm Lazy evaluation, a feature supported in most FP languages, can complicate I/O and debugging. Execution speed of Haskell and some other FP languages has also stymied adoption.
Module Code and Module Title Title of Slides Slide 40 (of 42)

Q&A

Any Questions?

Module Code and Module Title

Title of Slides

Slide 41 (of 42)

Next Session
Fundamental functional programming characteristics
Higher-order functions Pure functions and referential transparency Functional composition

Haskell Examples Simple exercises

Module Code and Module Title

Title of Slides

Slide 42 (of 42)

Das könnte Ihnen auch gefallen