Functional Lists in Groovy

Lately I’m reading books on functional programming languages ​​like Clojure and Erlang. There is a book for Erlang that covers all aspect of the language Programming Erlang. There is also one book(in spanish) very good for Erlang and is free from bosqueviejo. And for Clojure there are many like The Joy of Clojure or Functional Programming for the Object-Oriented Programmer.

What I’ve learned in these books is to think of another way to abstract problems and break them into reusable functions (also aspects such as concurrency, immutability and recursion).

Groovy has much functional style , in fact , the closures   for me is a clear example:


The functions that I will show below, I will add them to the class List dynamically by the metaclass. I think it’s better example that only show the functions , because then can reuse the functions in other parts of project.


For example, I will mimic the function map/2 from Erlang and I will add to the Groovy List class.

Map

Is a function that takes a function F and list L as arguments and returns the new list that is obtained by applying F to each of the elements in L.

I’ve done a bit tricky, because in reality the “map” function does not apply on a list already created, but I did so to show how to add a method to the List class dynamically. But I made ​​it more functional as possible, without modifying the original list and returning a new list( it is not inmutable, in Groovy to make a List inmutable call -> asInmutable() )

Be careful with add methods by metaClass , because if a method already exists with the same name it will be overwritten.

Let’s do another example, I’ll imitate the function pluck of Underscore.js .

Pluck

This function is the common use-case for map : extracting a list of property values.

As we see it is very easy to add functions to the Groovy List class, that are useful and / or we use a lot. In addition to obtain clean code, we can combine them to make still more powerful.

Note: If you use Grails these functions can be added dynamically with the Bootstrap.groovy ; so these functions can be used in all the classes of the project.

Comments