Thursday, October 4, 2007

Sequence Mapping Functions

I've slowly been making my way through Peter Seibel's Practical Common Lisp. Even though I'm also in between a few other books at the moment I've managed to let some of it soak in.

I came across the following example that shows off the quintessential map function.

1 (map 'vector #'* #(1 2 3 4 5) #(10 9 8 7 6))

It simply produces a new sequence by multiplying the subsequent elements of the supplied sequences, resulting in: => #(10 18 24 28 30)

To put it in perspective I decided to have a crack and see what an equivalent function would look like in Ruby. After a bit of mucking around I came up with this:

1 [1,2,3,4,5].zip([10,9,8,7,6]).map{|x,y| x * y}

I'm sure someone could probably come up with something nicer as there is more than one way to skin a cat in ruby (I haven't tried, honest - ..to skin a cat that is). Regardless I think we should all sit back and appreciate the aesthetics of the lisp map.

No comments: