Tuesday 19 August 2014

Scala Note 12: Functions


1. In Scala, a function is similar like a variable. Both can work as either argument or return value of a method. Any parameters passed in a function is immutable. For example, a string value won't be changed. Only will return a new string.

A function literal is compiled into a class that when instantiated at run-time is a function value.
The distinction between function literals and values is that function literals exist in the source code, whereas function values exist as objects at runtime.

 2. Both function and method can be defined by 'def'; 'val' can define an anonymous function, or an alias of a function.

def m0(x:Int) = x*x

val m1 = (x:Int)=> x*x 

val m2 = {x:Int=> x*x}

3.  If the function doesn't need return value.

def f() {...}  as the same as  def f():Unit = {...}

If return value is needed.
def f() = {...}  or   def f = {...}


Example:

1. Power Computation
def pow(n:BigInt, m:BigInt):BigInt = if (m==0) 1 else pow(n,m-1)*n

2. Hanoi Tower
def move(n:Int, src:Int, mid:Int, dist:Int) = {
  if (n==1) println("%s to %s" format (src, dist)) 
  else {
    move(n-1, src,dist,mid); 
    move(1,src,mid,dist); 
    move(n-1,mid,src,dist
}}







No comments:

Post a Comment