Functions


object FunctionsDay2 {
  println("Welcome to the Scala worksheet")       //> Welcome to the Scala worksheet
  
  def fact(x:Int) = {
  
  	def iter(n:Int, acc:BigInt) : BigInt =
  	if(n <= 2) acc else iter(n-1, n*acc)
  	iter(x,1)
  }                                               //> fact: (x: Int)BigInt
  fact(5)                                         //> res0: BigInt = 60
  
  def sum1(x:Int, y:Int) = {
  
  	def iter(n:Int, acc:BigInt) : BigInt =
  	if(n > y) acc else iter(n+1, n+acc)
  	iter(x,0)
  }                                               //> sum1: (x: Int, y: Int)BigInt
  sum1(1,10)                                      //> res1: BigInt = 55
  
  def sumSq(x:Int, y:Int) = {
  
  	def iter(n:Int, acc:BigInt) : BigInt =
  	if(n > y) acc else iter(n+1, n*n+acc)
  	iter(x,0)
  }                                               //> sumSq: (x: Int, y: Int)BigInt
  sumSq(1,10)                                     //> res2: BigInt = 385
    
  def sum(f: Int => Int, x:Int, y:Int) = {
  
  	def iter(n:Int, acc:BigInt) : BigInt =
  	if(n > y) acc else iter(n+1, f(n) + acc)
  	iter(x,0)
  }                                               //> sum: (f: Int => Int, x: Int, y: Int)BigInt
  
  def f1(n:Int) = n                               //> f1: (n: Int)Int
  def f2(n:Int) = n * n                           //> f2: (n: Int)Int
  
  sum(f1,1,10)                                    //> res3: BigInt = 55
  sum(f2,1,10)                                    //> res4: BigInt = 385
  
  sum(a => a,1,10)                                //> res5: BigInt = 55
  sum(b => b*b,1,10)                              //> res6: BigInt = 385
  
}