L15. Introduction to Scala

/*
Sintaxa basic:
 */
 
val s = "Hello World"
 
def fibo(n: Int): Int =
  if (n == 0) 0
  else if (n == 1) 1
  else fibo(n-1) + fibo(n-2)
 
// varianta tail-recursiva
// cum putem defini functii auxiliare (where)
def fibo1(n: Int): Int = {
 
  def fib_aux(n: Int,
              last: Int,
              before_last: Int): Int =
    if (n == 0) last
    else fib_aux(n-1,before_last+last,last)
 
  fib_aux(n,1,0)
}
 
fibo(3)
 
/* Functii de ordin superior */
 
def sumOf(start: Int, stop: Int): Int = {
  def auxSum(crt: Int, acc: Int): Int =
    if (crt > stop) acc
    else auxSum(crt+1,acc+crt)
 
  auxSum(start,0)
}
/*
   Daca vrem sa calculam, in loc de
   x1 + x2 + ... + xn
 
   x1^2 + x2^ + ... xn^2
 
   f(x1) + f(x2) + ... + f(xn)
 
   Ce ar trebui sa facem ?
 */
 
def sumWithf (f: Int => Int,
              start: Int,
              stop: Int): Int = {
  def aux(crt: Int, acc: Int): Int =
    if (crt > stop) acc
    else aux(crt+1,acc+f(crt))
  aux(start,0)
}
 
def id (x: Int): Int = x
def square(x: Int): Int = x * x
 
sumWithf(x => x,0,10)
sumWithf(square,0,10)
 
/*
Cum definim functii anonime?
 */
(x: Int) => x // lambda x.x (peste intregi)
//x => x       // peste orice tip
 
(x: Int, y: Int) => x + y
 
/* un short-hard pt functii anonime */
val f: (Int,Int) => Int = _ + _
 
// nu putem scrie (x,y) => y + x folosind shorthand-ul anterior
 
val g: Int => Int = _ + 1
 
/* curry vs uncurry */
 
def uncurry(x: Int, y: Int, z: Int): Int = x + y + z
 
def curry(x: Int): Int => (Int => Int) = {
  def g(y: Int): Int => Int = {
    def h(z: Int): Int = x + y + z
    h
  }
  g
}
 
def curryNice(x: Int)(y: Int)(z: Int): Int = x + y + z
 
curry(1)(2)
val f: Int => Int = curryNice(1)(2)
 
def withf (f: Int => Int)(
              start: Int,
              stop: Int): Int = {
  def aux(crt: Int, acc: Int): Int =
    if (crt > stop) acc
    else aux(crt+1,acc+f(crt))
  aux(start,0)
}
 
//aduna valori dintr-un range
val fun : (Int,Int) => Int = withf(x => x)
val fun2 : (Int,Int) => Int = withf(x => x*x)
val fun3 : (Int,Int) => Int = withf(3*_)