Click here to load reader
Upload
cao-manh-dat
View
47
Download
2
Embed Size (px)
DESCRIPTION
functional programming
Citation preview
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
High-order funtion
• Function
– as paramters
– as result
=> Currying : f(x,y) => z = g(x)(y) => z
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
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
Exercise 1
• Rewrite factorial as tail-recursion
Think about loop in different way
• Basically for loop = f(c) with c is a collection
Think about loop in different way (2)
Does a string have an uppercase character
Java
Scala
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)
Think about loop in different way (4)
• exists
• filter
• find
• forall
• foreach
• map
• reduce