Pergunta

It is a commonplace when one needs to accumulate some data. The way I get used to do it is appending data chunks to array. But it's a bad practice in scala, so how can I avoid it?

Foi útil?

Solução

Well, there are two generic ways of dealing with accumulation: recursion and folding. Let's look into very simple examples of each, to compute the sum of values of a list.

def sumRecursively(list: List[Int]): Int = {
  def recurse(list: List[Int], acc: Int): Int =
    if (list.isEmpty) acc
    else recurse(list.tail, acc + list.head)
  recurse(list, 0)
}

def sumFolding(list: List[Int]): Int =
  list.foldLeft(0){ case (acc, n) => acc + n }

There are many variations on this, which handle better one case or another.

Outras dicas

Actually, it isn't. You can use a Vector in scala which is part of the scala.collection.immutable package by default. That will create an immutable collection that returns a new (different) instance every time you append to it.

More information:

http://www.scala-lang.org/docu/files/collections-api/collections_15.html

For most common uses, the "map" and "flatMap" operations are used to functionally generate data structures. Both start with one data structure, apply some operation to each element in it, and return a new data structure of the same shape as the original. They differ in just how the new data structure is populated. These two are so common and so powerful that Scala includes a special syntax, the for-comprehension, to support them. The for-comprehension looks superficially similar to a Java-style for-loop, but actually compiles to a series of map and flatMap calls (among a few others).

In functional programming, it is common to break down your problem into transformations like this from one data structure to another, rather than explicitly describing the steps necessary to build and destroy your data structures. This takes some getting used to, particularly in figuring out what data structure to start wit. Once you master it this is extremely powerful technique, allowing large chunks of functionality to be expressed clearly, precisely, and with little room for bugs to creep in.

It's also worth noting that both "map" and "flatMap" are actually special cases of another, more powerful function: "fold". "fold" (implemented as both "foldLeft" and "foldRight", for technical reasons) can be used to both build up data structures and break them down.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top