Question

I'm a novice in Scala. I am trying to do the following stuff:

def foo(n: Int): List[Int] = {
  def worker(i: Int, acc: List[Int]): List[Int] = {
    if (i == 0) acc
    else worker(i - 1, compute(i) :: acc)
  }
  worker(n, List[Int]())
} 
  • foo iterates from 0 to n
  • For each iteration, it updates/accumulates on an immutable list.

What I want to do is expressing more succinctly using something like foldLeft.

If foo iterates over a List, high-order transform functions such as map and reduceLeft could be used. I may exploit this kind of functions, but want to know whether there is more elegant way to this kind of task.

A corresponding code in C++ would look like:

list<int> foo(int n) {
  list<int> result;
  for (int i = 0; i < n; ++i)
    result.push_back(compute(i));
  return result;
}
Was it helpful?

Solution

How about:

def foo2(n: Int) = (1 to n).foldLeft(List[Int]())((l,i) => l :+ compute(i))

or even:

def foo2(n: Int) = (1 to n).foldLeft(List[Int]())(_ :+ compute(_))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top