fp handout

Upload: silver-bullet

Post on 08-Jan-2016

218 views

Category:

Documents


0 download

DESCRIPTION

lap trinh ham

TRANSCRIPT

  • Functional Programming in Scala

    Dr. Nguyen Hua Phung

    HCMC University of Technology, Viet Nam

    06, 2014

    Dr. Nguyen Hua Phung Functional Programming in Scala 1 / 39

  • Outline

    1 FP Introduction

    2 Higher-order Functions

    3 Immutability

    4 Expression

    5 Pattern Matching

    6 Recursion

    7 Lazy evaluation

    8 Type Inference

    9 Partial Function

    Dr. Nguyen Hua Phung Functional Programming in Scala 2 / 39

  • Functional Programming

    Function are values, i.e., a function can beValue Function

    Anonymous 3 x => x + 1 Assigned to a variable x = 3 f = x => x + 1 Passed as input/outputparameter f(3) f(x => x + 1) Created dynamically 3 + 4 f g

    Dr. Nguyen Hua Phung Functional Programming in Scala 4 / 39

  • Fundamental Theory

    Imperative languages Von Neumann ArchitectureEfficiency

    Functional languages Lambda CalculusA solid theoretical basis that is also closer to the user,butrelatively unconcerned with the architecture of themachines on which programs will run

    Dr. Nguyen Hua Phung Functional Programming in Scala 5 / 39

  • Mathematical Functions

    A mathematical function isa mapping of members of one set, called the domainset, to another set, called the range set

    A lambda expression specifies the parameter(s)and the mapping of a function in the following form(x) x * x * xfor the function cube cube(x) = x * x * xLambda expressions describe nameless functionsLambda expressions are applied to parameter(s) byplacing the parameter(s) after the expression((x) x * x * x)(2) which evaluates to 8

    Dr. Nguyen Hua Phung Functional Programming in Scala 6 / 39

  • Higher-order Functions

    A higher-order function is one that either takesfunctions as parameters or yields a function as itsresult, or bothFor example,

    Function compositionApply-to-allForall/ExistsInsert-left/Insert-rightFunctions as parametersClosures

    Dr. Nguyen Hua Phung Functional Programming in Scala 8 / 39

  • Function Composition

    A function thattakes two functions as parameters andyields a function whose value is the first actualparameter function applied to the application of thesecondf g = f : (g : x)For f(x) = x + 2; g(x) = x * x; f g = x * x + 2

    Example in Scala,

    val f = (x:Double) => x + 2val g = (x:Double) => x * xval h = f compose gh(3)val k = f andThen gf(3)

    Dr. Nguyen Hua Phung Functional Programming in Scala 9 / 39

  • Apply-to-all

    A functional form thattakes a single function as a parameter andyields a list of values obtained by applying the givenfunction to each element of a list of parameters

    f :< x1, x2, ..., xn >=< f : x1, f : x2, ..., f : x2 >

    For h(x)=x*x h:(1,2,3) yields (1,4,9)Example in Scala,

    List(2,3,4).map((x:Int) => x * x)def inc (x:Int) = x + 1List(4,5,6).map(inc)

    Dr. Nguyen Hua Phung Functional Programming in Scala 10 / 39

  • Forall/Exist

    A functional form thattakes a single predicate function as a parameter andyields a value obtained by applying the given functionto each element of a list of parameters and take theand/or of the results

    f :< x1, x2, ..., xn >=

    f : xif :< x1, x2, ..., xn >=

    f : xi

    Example in Scala,

    def isEqualToThree(x:Int) = x == 3List(2,3,4).forall(isEqualToThree)

    // yield falseList(2,3,4).exists(isEqualToThree)

    // yield true

    Dr. Nguyen Hua Phung Functional Programming in Scala 11 / 39

  • Insert Left / Insert Right

    /f :< x0 >,< x1, x2, ..., xn >

    f

    ...

    f

    f

    x0 x1

    x2

    xn

    \f :< x0 >,< x1, x2, ..., xn >

    f

    x1 ...

    f

    xn1 f

    xn x0

    Dr. Nguyen Hua Phung Functional Programming in Scala 12 / 39

  • Insert Left / Insert Right (contd)

    Example in Scala

    List(2,3,4).foldLeft(0)((a,b) => a+b) // yield 9List(2,3,4).foldLeft(1)((a,b) => a*b) // yield 24List(2,3,4).foldLeft("A")((a,b) => a + b)

    // yield "A234"List(2,3,4).foldRight("A")((a,b) => a + b)

    // yield "234A"

    Dr. Nguyen Hua Phung Functional Programming in Scala 13 / 39

  • Functions as Parameters

    In user-defined functions, functions can be passed asparameters.

    def apply(x:Int)(f:Int=>Int) = f(x)val inc1 = (x:Int) => x + 1val sq = (x:Int) => x * xval fl = List(inc1,sq)fl.map(apply(3)) //yield List(4,9)

    Dr. Nguyen Hua Phung Functional Programming in Scala 15 / 39

  • Closure [1]

    "An object is data with functions. A closure is a functionwith data." - John D. Cook

    def power(exp:Double) =(x:Double) => math.pow(x,exp)

    val square = power(2)square(4) //yield 16.0val cube = power(3)cube(3) //yield 27.0

    Closure = function + binding of its free variables

    Dr. Nguyen Hua Phung Functional Programming in Scala 16 / 39

  • Currying functions [2]

    f : X1 X2 ... Xn Ycurry: f : X1 X2 ... Xn YExample in Scala

    def add(x:Int, y:Int) = x + yadd(1,3)add(1) add(1)(3)def plus(x:Int)(y:Int) = x + yplus(1)(3)val inc1 = plus(1) _inc1(3)val addCurried = (add _).curriedval plusUncurried = Function.uncurried(plus _)

    Read more on Partially Applied Functions [2]

    Dr. Nguyen Hua Phung Functional Programming in Scala 17 / 39

  • Immutability

    Immutable: Cannot changeIn Java, strings are immutable"Hello".toUpper() doesnt change "Hello" but returns anew string "HELLO"In Scala, val is immutableval num = 12num = 10 // wrongPure functional programming: No mutationsDont mutatealways return the result as a newvalueFunctions that dont mutate state are inherentlyparallelizable

    Dr. Nguyen Hua Phung Functional Programming in Scala 19 / 39

  • Example on Immutability

    abstract class IntStackdef push(x: Int): IntStack =

    new IntNonEmptyStack(x, this)def isEmpty: Booleandef top: Intdef pop: IntStack

    class StackEmpty extends IntStackdef isEmpty = truedef top = error("EmptyStack.top")def pop = error("EmptyStack.pop")

    class IntNonEmptyStack(elem: Int, rest: IntStack)extends IntStack

    def isEmpty = falsedef top = elemdef pop = rest

    Dr. Nguyen Hua Phung Functional Programming in Scala 20 / 39

  • Everything is an expression

    Body of a function is an expression, i.e. evaluating toa valueIf there are many expressions, the value of the lastexecuted expression will be returnedNo return required

    Example in Scala,

    def fact(x:Int):Int =if (x == 0) 1 else x * fact(x - 1)

    val s = for (x 50) yield 2*x

    Dr. Nguyen Hua Phung Functional Programming in Scala 22 / 39

  • Pattern Matching [3]

    Like switch, but much more powerful

    Syntax: match {case => case => ...}Example in Scala,

    def mathTest(x : Int): String = x match {case 1 => "one"case 2 => "two"case _ => "many"

    }

    Dr. Nguyen Hua Phung Functional Programming in Scala 25 / 39

  • Recursion

    With recursive functions, return type is obligateddef fact(n:Int):Int = if (x == 0) 1 else n * fact(n - 1)Need def because the name is used on the rightIteration (while, for) can always be expressed asrecursion

    Example in Scala,

    def mem(x:Int,lst:List[Int]):Boolean = lst match {case List() => falsecase head :: tail => if (x == head) true

    else mem(x,tail)}

    Dr. Nguyen Hua Phung Functional Programming in Scala 27 / 39

  • Lazy evaluation [4]

    Expressions are eagerly evaluated, by default, wherethey appearedLazy evaluation means the expression is justevaluated when the associated variable is firstlyreferred.lazy val x = 1 + yThe expression 1 + y is evaluated just when x is firstlyusedPass-by-name parameterdef foo(b:Boolean,x:=>Int,y:=>Int) = if (b) x else yfoo(a==0,1,b/a)

    Dr. Nguyen Hua Phung Functional Programming in Scala 29 / 39

  • Type Inference

    Scala is strongly typed. Any value has a typeguaranteeJust like C++:char* greeting = "Hello";greeting = 42;//Type ErrorBut without having to declare types:val greeting = "Hello";Contrast with scripting languages such as JavaScriptvar greeting = Hello;//This is JavaScriptgreeting = 42;//Okalert(greeting.length);//Runtime Error

    Dr. Nguyen Hua Phung Functional Programming in Scala 31 / 39

  • Type Inference (contd)

    Can override inferred type (only to a supertype, ofcourse).var greeting : Any = "Hello"greeting = 42//OkParameter type must be declareddef mistery (x) = 42 * x // Errordef mistery (x : Int) = 42 * x // OkReturn type can be inferredIf x is Int, then 42 * x is also IntException, recursive function requires return typedeclared

    Dr. Nguyen Hua Phung Functional Programming in Scala 32 / 39

  • Parameter Inference from Context

    When a function parameter type is known, ananonymous function can be supplied withoutspecifying its parameter typesdef twice(f: (Int)=>Int,x:Int) = f(f(x))twice(x=>42*x, 3) // Ok, x:Int is inferred from contextVery useful when calling library functionsList(1,2,3).filter(x=> x%2==0)

    List[A].filter(p:(A)=>Boolean) : List[A]A is Int since List(1,2,3) is a List[Int]p: must be (Int) => BooleanX must be Int

    Dr. Nguyen Hua Phung Functional Programming in Scala 33 / 39

  • Parameter Simplification

    Ok to omit () around a single inferred parameterList(1, 2, 3).filter(x => x % 2 == 0)List(1, 2, 3).sortWith((x,y) => x > y)// need () with 2 or more parametersUse _ for a parameter that occurs only once in a bodyList(1, 2, 3).filter(_ % 2 == 0)List(1, 2, 3).sortWith( _ > _)

    Dr. Nguyen Hua Phung Functional Programming in Scala 34 / 39

  • Partial Function

    a partial function from X to Y (f: X 9 Y) is a functionf: X Y, for some subset X of X.

    :Z Z is a partial function.Partial function in Scala is different from PartiallyApplied Function concerned in Slide "CurryingFunction"

    Example in Scala,

    type PF = PartialFunction[Int,String]val one : PF = {case 1 => "one"}one.isDefinedAt(1) //yield trueone.isDefinedAt(2) //yield falseval two: PF = {case 2 => "two"}val oneOrTwo = one orElse twoval any: PF = {case _ => "any number"}val num = one orElse two orElse any

    Dr. Nguyen Hua Phung Functional Programming in Scala 36 / 39

  • Summary

    Functional programming languages use functionapplication, conditional expressions, recursion,and functional forms to control program executioninstead of imperative features such as variables andassignmentsPurely functional languages have advantages overimperative alternatives, but their lower efficiency onexisting machine architectures has prevented themfrom enjoying widespread use

    Dr. Nguyen Hua Phung Functional Programming in Scala 38 / 39

  • References I

    [1] Methods and Closures, http://www.artima.com/pins1ed/functions-and-closures.html, 19 06 2014.

    [2] Function Currying in Scala, http://www.codecommit.com/blog/scala/function-currying-in-scala, 19 06 2014.

    [3] Case classes and pattern matching,http://www.artima.com/pins1ed/case-classes-and-pattern-matching.html, 19 06 2014.

    [4] Control Abstraction, http://www.artima.com/pins1ed/control-abstraction.html, 19 06 2014.

    Dr. Nguyen Hua Phung Functional Programming in Scala 39 / 39

    FP IntroductionHigher-order FunctionsImmutabilityExpressionPattern MatchingRecursionLazy evaluationType InferencePartial Function