A few basic examples
def myAddition(x: Int, y: Int): Int = x + y
myAddition(1,2)
def inRange(start: Int, stop: Int, x: Int): Boolean =
if (x <= stop && x >= start) true
else false
def inRange1(start: Int, stop: Int, x: Int): Boolean =
x <= stop && x >= start
def and(x: Boolean, y: Boolean): Boolean =
if (x) y else false
and(false, true)
false && true
Non-tail recursive functions
def fact(n: Int): Int =
if (n == 1) 1
else n * fact(n-1)
def fibo(n: Int): Int =
if (n == 0) 0
else if (n == 1) 1
else fibo(n-1) + fibo(n-2)
Tail-recursive functions
def tail_fact(n: Int): Int = {
def aux_fact(n: Int, acc: Int): Int =
if (n == 1) acc
else aux_fact(n-1, acc * n)
aux_fact(n,1)
}
def fibo1(n: Int): Int = {
// local (inner) function definition
def fib_aux(n: Int, // nth fibonacci number
last: Int, // the last fibonacci number
before_last: Int // the previous one
):Int =
if (n == 0) before_last
else fib_aux(n-1,last + before_last,last)
// the code block evaluates to the function call below:
fib_aux(n,1,0)
}