Saturday 19 September 2015

Partially Applied Functions v.s. Partial Functions v.s. Currying

1. Partially applied function

For a function with more than one argument list, you can define a new function if you omit one or more of the trailing argument lists. A partially applied function is an expression with some, but not all of a function's argument lists applied, returning a new function that takes the remaining argument lists. Scala requires the trailing underscore to tell the compiler that you really meant to do this.
Note that you're not allowed to omit trailing arguments within a single argument list and then apply them later.

Example,

def cat1(s1: String)(s2: String) = s1 + s2

val hello = cat1("hello")_
hello("word")

2. Partial function

A partial function is a single-arguemnt function that is not defined for all values of the type of its argument. The literal syntax for a partial function is one or more case match clauses enclosed in curly braces.

Since PartialFunction extends Function1, which means the first type is for input, the second type is for return.

Example,

val inverse: PartialFunction[Double, Double] = {
      case d if d!= 0.0 => 1.0 / d
}

inverse(1.0)


Partial functions are partial in the sense that they aren't defined for all possible inputs, only those inputs that match at least one of the specified case clauses.
Only case clauses can be specified in a partial function and the entire function must be enclosed in curly braces. If the input doesn't match one of the case clauses, a MatchError is thrown at runtime.


3. Curried Function

Currying transforms a function that takes multiple arguments into a chain of functions, each taking a single argument.

scala> def cat2(s1: String) = (s2: String) => s1 + s2
cat2: (s1: String)String => String

scala> val cat2hello = cat2("Hello ") //No _
cat2hello: String=>String = <function1>

Currying and partially applied functions are closely related concepts. They are referred to almost interchangeably, but what's important is their application.
Example:

def multiplier(i:Int)(factor:Int)= i* factor
val byFive = multiplier(5)_
val byTen = multiplier(10)_
byFive(2)
byThen(2)



No comments:

Post a Comment