Saturday, October 02, 2010

Clojure sequence comprehensions

I am learning Clojure and I like it. Following the ThinkRelevance functional koans has given me a really good interactive playground for learning this language. Reading through examples in a book cannot compare to actually having to write code in order to solve a problem and in the process learn syntax and the rules of a language. What a concept!

I came across something in the sequence comprehensions section that I thought was interesting.

(= [[:top :left] [:top :middle] [:top :right]
[:middle :left] [:middle :middle] [:middle :right]
[:bottom :left] [:bottom :middle] [:bottom :right]]
(for [row [:top :middle :bottom] column [:left :middle :right]]
[row column])))
view raw snippet.clj hosted with ❤ by GitHub

The "for" macro can loop over one (or more) groups of things and produce the vector combinations above. I was reminded while reading this of Ruby's Array#product method, which does the same thing (return the product of 2 or more arrays).

[:top, :middle, :bottom].product [:left, :middle, :right]
# produces
[[:top, :left], [:top, :middle], [:top, :right],
[:middle, :left], [:middle, :middle], [:middle, :right],
[:bottom, :left], [:bottom, :middle], [:bottom, :right]]
view raw snippet.rb hosted with ❤ by GitHub

2 comments:

James Carr said...

Did you start getting into it because of the exposure at code retreat? :)

Mario said...

Definitely. I gave emacs a brief try after the event but I gave up after not too long. I want to get back to it when I have more regular access to someone skilled in the ways of that fine tool.