[beginning-scala-programming] Function & Recursion


Functions

val a = 5

def square(x:Double) : Double = x*x  // def {name}({paramname} :{paramtype}) : {return type} = {function}

square(a) // res0 : Double = 25.0
{ 3
4
5} // res0:Int = 5
def greet(name:String):Unit = { // Unit : doesn’t return anything (생략 가능)
     pintln(s"Hello, $name")
}

greet("Mark") // Hello, Mark

Recursion

// n! = n * (n-1) * (n-2) * … * 3 * 2 * 1
def factorial(n:Int):Int = if(n<2) 1 else n*factorial(n-a)
factorial(3)
def estimatePi(n:Int):Double = {
     def helper(n:Int):Double = {
          if(n<1) 0 else {
          val x = math.random
          val y = math.random
               (if(x*x+y*y<1) 1 else 0 ) + helper(n-1)
          }
          helper(n)/n*4
     }
}

estimatePi(1000) // StackOverFlow Exception occured
import scala.annotation._

def estimatePi(n:Int):Double = {
     @tailrec
     def helper(n:Int, sum:Int):Double = {
          if(n<1) sum else {
          val x = math.random
          val y = math.random
          helper(n-1, sum+if(x*x+y*y<1) 1 else 0 )
          }
          helper(n)/n*4
     }
}

estimatePi(1000) // Nothing exception appeared.

참고 : puruni/Recursion.scala