this post gets continuously updated
The equivalent Scala code looks like:
def f(x: Int): Int = x+1
@tailrec
so that the
compiler will succeed only if the function is indeed tail recursive.
Refer Tail Recursion Explained - Computerphile// function to get the nth Fibonacci number
def fib(n: Int): Int = {
@tailrec
def loop(n1: Int, n2: Int, i: Int): Int = {
if (i == n) n1
else loop(n2, n1+n2, i+1) // <- tail call
}
loop(0, 1, 0)
}
polymorphic/generic function: A generic function is a function that is declared with type parameters. When called, actual types are used instead of the type parameters.
Following code snippet is an example for polymorphic function (since it is generic over the data type A
) and higher order function (since the second parameter it takes has to be a function).
def findFirst[A](as: Array[A], p: A => Boolean): Int = {
@tailrec
def loop(n: Int): Int = {
if (n >= as.length) -1
else if (p(as(n))) n
else loop(n+1) // <- tail call
}
loop(0)
}
// the 'x => x == 5' is an anonymous function
findFirst[Int](Array(1,2,3,4,5), x => x == 5) //4
findFirst[String](Array("a", "b", "c"), x => x == "c") //2
Another example of anonymous functions
val square: Int => Int = x => x * x
// OR
val square = (x:Int) => x * x
square(2) // 4
square(3) // 9
def square(x: Int): Int = x * x
val result = square(2 + 2)
In this code, the square function takes an Int argument and returns the square
of that argument. When the square function is called with the argument 2 + 2
,
the argument is evaluated first, and the result is 4
. Then, the square function
is applied to the value 4
, and the result is 16
.
def square(x: => Int): Int = x * x
val result = square(2 + 2)
In this code, the square
function takes an Int
argument, but the argument is preceded by the =>
symbol. This indicates that the argument is evaluated by-name, rather than by-value. When the square function is called with the argument 2 + 2
, the argument is not immediately evaluated. Instead, the square function is applied to the unevaluated argument 2 + 2
, and the result is 4 * 4
or 16
.
First published on 1st December 2022