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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(= [[: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]))) |
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[: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]] |
2 comments:
Did you start getting into it because of the exposure at code retreat? :)
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.
Post a Comment