Recursion
Exercise 1 sum
Write a function that takes a positive integer n and returns the sum of all the integers from 1 to n.
def sum(n: Int): Int =
if n <= 1 then n
else n + sum(n - 1)
// example usage
sum(5) // returns 15
Exercise 2 sumBetween
Write a function that takes two integers and returns the sum of all the integers between them, including the endpoints.
def sumBetween(x: Int, y: Int): Int =
if x == y then x
else x + sumBetween(x + 1, y)
// example usage
sumBetween(1, 5) // returns 15
Exercise 3 sumList
Write a function that takes a list of integers and returns the sum of all the integers in the list.
def sumList(list: List[Int]): Int = {
if list.isEmpty then 0
else list.head + sumList(list.tail)
}
// example usage
sumList(List(1, 2, 3, 4, 5)) // returns 15
Exercise 4 filter even
Write a function that takes a list of integers and returns a new list with all the even numbers.
def filterEven(list: List[Int]): List[Int] =
if list.isEmpty then List()
else if list.head % 2 == 0 then
list.head :: filterEven(list.tail)
else
filterEven(list.tail)
// example usage
filterEven(List(1, 2, 3, 4, 5, 6)) // returns List(2, 4, 6)
Exercise 5 longest string
Write a function that takes a list of strings and returns the length of the longest string in the list.
def longestString(list: List[String]): Int =
if list.isEmpty then 0
else
list.head.length.max(longestString(list.tail))
// example usage
longestString(List("apple", "banana", "orange", "pear")) // returns 6