Nov 15, 2008

Using Reduce as a Decorator

A while back I wrote a post about reduce, which is a technique used in functional languages to get a single value from a list.

While one main use of this is for things like summation or finding a max/min of a list, it can be used in other ways too. One neat thing that I discovered you can do is apply the decorator pattern with reduce (this example is in Ruby which calls it inject):
decorators = [Mocha, Whip, TonsOfSugar]
new_coffee = decorators.inject(old_coffee) { |coffee, dec| dec.new coffee }
I thought this was pretty cool, and realized that it can be used in a more general case. If you have a set of transformation functions in an array, and you can apply them all using just this one line:
result = transforms.inject(original) { |o, t| t.call o }
One example I found is if you have a string, and a set of replacements to apply to it (could be stored as a hash), you can do it like this:
replacements = {"a" => 1, "b" => 2, "c" => 3}
original = "abcdefg"
result = replacements.inject(original) { |string, repl| string.gsub(repl[0].to_s, repl[1].to_s) }
puts result # outputs 123defg
This is probably old news for FP folks, but to us young'ns it's an interesting discovery!

No comments: