Buscar en Mind w/o Soul

jueves, abril 26, 2007

Uso práctico de closures

Argumentos-bloque de código, list comprehensions, lambdas en Ruby, Python, Smalltalk

http://www.martinfowler.com/bliki/CollectionClosureMethod.html
http://www.martinfowler.com/bliki/Closure.html

The next most common closure method I use with collections is collect. This is similar but where you need to gather the results of a method call. Here's the traditional code:

  offices = []
for e in employees
offices <<>

Again the closure method allows you to use a one-liner.

offices = employees.collect {|e| e.office}

You can see what this does, it's similar to select but instead puts the result of the method call into the returned collection. Smalltalk also called this 'collect'. Lisp has a similar function called 'map', in ruby 'map' is an alias for 'collect'.

There's a concept that's come out of modern functional programming languages that's similar to the two preceding closure methods - it's called a list comprehension. List comprehensions have made their way into the python language. They provide a syntactic approach to getting the kinds of benefits we've seen so far. Here are the two examples again using python list comprehensions.

  managers = [e for e in employees if e.isManager]
offices = [e.office for e in employees]

List comprehensions make it easy to combine the two.

managersOffices = [e.office for e in employees if e.isManager]

  total = 0
for e in employees
total += e.salary
end

Inject does it like this.

total = employees.inject(0) {|result, e| result + e.salary}

At each element in the collection inject assigns the result of executing the block to the result variable. The result of the final execution gets returned from inject.

No hay comentarios: