Forked from an inaccessible project.
-
Olivier Blanvillain authoredOlivier Blanvillain authored
recitation-session-1.md 1.40 KiB
Recitation Session 1
We will work on tail recursion in this session.
Exercise 1: Factorial
Recall the factorial function that you saw in class
def factorial(n: Int): Int = if (n <= 0) 1 else n * factorial(n - 1)
Define a tail recursive version of it
def factorial(n: Int): Int = fact(n, 1)
@tailrec
def fact(n: Int, acc: Int): Int = ???
What would be the advantage of making fact
an inner function to factorial
?
Exercise 2: Sum of elements on a list
Define a function that takes a list of integers and sums them. You can use the functions head
, tail
, and isEmpty
on lists, as you have seen for your homework.