Traversable ops – Fold *

This is the first of a series of blog entries related to the most common operations in Scala’s functional programming world: operations belonging to the Traversable API.
strong>Traversable is considered to be the basis of all Scala collections and is characterized mainly by two features:

  • Strictness: All elements have to be computed previously for them to be treated as values.
  • Orderness: Elements keep an order between them.

There are other types of collections, such as Streams, which have a lazy evaluation strategy, but let’s not lose focus. Today, we will talk about fold operation… without getting worked up, without breaking down.

nlY1Wxv

Suppose we want to concatenate numbers from 1 to 5 in a text string, getting the result “My numbers are: 12345”. What would our first approach be? It could be something like this:

var initial: String = "My numbers are: "
for(i <- 1 to 10){
  initial = initial + i.toString
}

his would work. But you can imagine how nasty the variables would look like.

40HYLZX

Don’t you worry. The operation that can be used to replace the above loop is fold, which has two varieties: foldLeft and foldRight. While the first operation acts on the Traversable in an element by element iterative way, the second one does it recursively, thus being unadvisable to use this last one if the target collection is considerably large. We will focus, then, on the first operation.

he notation of foldLeft for a given Traversable[T] is:

def foldLeft[U](zero: U)(f: (U,T) => U): U

If we put it this way, it may seem a little bit difficult to understand. So, let’s apply the operation to the previous example:

‘Zero’ element would be in this case the initial text string “My numbers are:” (String type). And the function to be applied to each pair of (String, Int) would be concatenation.

Thus, we would be able to express the first code snippet, without using any variable at all, in the following way:

(1 to 5).foldLeft("My numbers are: ")(
  (accumulator,iterator) => accumulator + iterator.toString)

For those who think that this syntax is too mainstream, there is an alternative notation to perform the same operation:

("My numbers are: " /: (1 to 5))((accumulator,iterator) =>
  accumulator + iterator.toString)

Easy, simple and for the entire family 🙂

Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s