10

Click here to load reader

Functional programming

Embed Size (px)

DESCRIPTION

functional programming

Citation preview

Page 1: Functional programming

Functional Programming

Page 2: Functional programming

Idea

• Restricted sense, a functional programming language is one which does not have mutable variables, assignments, or imperative control structures.

• Wider sense, a functional programming language enables the construction of elegant programs that focus on functions. So it will be easier to be distributed

Page 3: Functional programming

High-order funtion

• Function

– as paramters

– as result

=> Currying : f(x,y) => z = g(x)(y) => z

Page 4: Functional programming

Quiz

//greatest common divisor of two numbers

def gcd(a:Int, b:Int): Int =

if (b==0) a else gcd(b, a%b)

//factorial number

def factorial(n:Int): Int =

if (n==0) 1 else n*factorial(n-1)

What is different between recursion call of gcd and factorial

Page 5: Functional programming

Tail recursion

• “If a function calls itself as its last action, the function’s stack frame can be reused”

=> Never be stackoverflow again with recursion

• All recursion can be rewrite to tail recursion

Page 6: Functional programming

Exercise 1

• Rewrite factorial as tail-recursion

Page 7: Functional programming

Think about loop in different way

• Basically for loop = f(c) with c is a collection

Page 8: Functional programming

Think about loop in different way (2)

Does a string have an uppercase character

Java

Scala

Page 9: Functional programming

Think about loop in different way (3)

Return all even member of a collection and time 2

Java : Cannot fit this slide (shame on you, java)

Scala

val rs = input.filter(_%2==0).map(_*2)

Page 10: Functional programming

Think about loop in different way (4)

• exists

• filter

• find

• forall

• foreach

• map

• reduce