"Hello world"
// in Scala (FP in general)
// fiecare bucata de cod este
// O EXPRESIE si ea se evalueaza
// la ceva TOT TIMPUL.
var x = 0
if (x > 0) 1 else 0
// efecte laterale (side effects)
// calculam suma tuturor numerelor de la 0 la 10
var sum = 0
for (i <- 0 to 10)
sum += i
sum
// functie recursiva
def sumTo(start: Int, stop: Int): Int =
if (start > stop) 0
else start + sumTo(start+1,stop)
sumTo(0,10)
def tail_sumTo(start: Int, stop: Int): Int = {
def loop (i: Int, sum: Int): Int =
if (i > stop) sum
else loop(i+1, sum+ i)
loop(start,0)
}
//factorial
var fact = 1
for (i <- 1 to 5)
fact *= i
fact
def fact(n: Int): Int =
if (n == 1) 1
else n*fact(n-1)
def tail_fact(n: Int): Int = {
def loop(i: Int, crt_fact: Int): Int =
if (i > n) crt_fact
else loop(i+1,i*crt_fact)
loop(1,1)
}
tail_fact(10)
// nrele lui Fibonacci
// f0 = 0, f1 = 1
// fn = f{n-1} + f{n-2}
var bf_last = 0
var last = 1
var n = 5
for (i <- 0 to n-2){
var aux = last + bf_last
bf_last = last
last = aux
}
last
def fibo(n: Int): Int =
if (n == 0) 0
else if (n == 1) 1
else fibo(n-1)+fibo(n-2)
def tail_fibo(n: Int): Int = {
def loop(i: Int,
before_last: Int,
last: Int): Int = {
if (i > n-2) last
else loop(i+1,last,before_last+last)
}
loop(0,0,1)
}
tail_fibo(500)