Here are some solutions in Scala for typical problems with Lists that may arise when developing larger tasks, these ones can become repetitive over time and they could be used as a “recipe”. Also, they’re classic/basic problems for practice.
- Five different ways to create a function that returns a list of N elements:
def a(n: Int): List[Int] = List.fill(n)(1) def b(n: Int): List[Int] = (1 to n).toList def c(n: Int): List[Int] = if(n == 0) Nil else n :: c(n-1) def d(n: Int): List[Int] = List.tabulate(n)(n => 1) def e(n: Int): List[Int] = List.range(0,n)
- Create a function that reverses a list without using the native Scala reverse method:
def rev(l: List[Any]): List[Any] = l match { case Nil => l case head :: tail => rev(tail) ::: List(head) }
- Given a list, repeat each element in the list N amount of times:
def f(n: Int, ls: List[Int]): List[Int] = ls.flatMap(List.fill(n)(_))
- Filter a given list of integers and output only those values that are less than a specified value:
def g(delim: Int, ls: List[Int]): List[Int] = for(i <- ls if i < delim) yield i
- For a given list with N integers, return a new list removing the elements at odd positions:
def removeOdds(ls: List[Int]): List[Int] = {ls.zipWithIndex.filter(_._2 % 2 != 0).map(_._1)}
- Create a function that returns the sum of the odd elements from a list:
def sumOdds(ls: List[Int]): Int = ls.filter(x => x % 2 != 0).sum
- Create a function that returns the size of a list of integers without using the native Scala length method:
def s(ls: List[Int]): Int = { var size = 0 for(i <- ls) size = size + 1 size }