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;
}

1 Answer 1

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(_))
Sign up to request clarification or add additional context in comments.

1 Comment

+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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.