0

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;
}
minjang
  • 8,860
  • 9
  • 42
  • 61

1 Answers1

2

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(_))
Shadowlands
  • 14,994
  • 4
  • 45
  • 43
  • +1 but if you don't need to accumulate, just use `map`. e.g. `(0 until n) map (compute)`. Reader should keep performance characteristics of List in mind. `:+`, or `append`, is O(n). `foldRight` may be nicer for this example as you can prepend and keep correct order but general case is recursive (and not of the tail kind). – drstevens Oct 17 '13 at 06:40