Search code examples
clojuresequences

Clojure Koans: Trouble Understanding the Section on Sequence Comprehensions


I'm new to Clojure, so I've been going through the Clojure Koans the last few days. Things were going fairly well until the section on sequence comprehensions. I'm struggling with this section. The answers are available, but I don't understand how they arrived at these answers. I've read quite a bit about Clojure the last two days, but it's so much different than Ruby that it's taking me a while to understand it.

There are five "problems" in the section and I can't figure them out. Here are two examples of problems that particularly confused me:

"And also filtering"
(= '(1 3 5 7 9)
  (filter odd? (range 10))
  (for [index __ :when (odd? index)]
    index))

"And they trivially allow combinations of the two transformations"
(= '(1 9 25 49 81)
  (map (fn [index] (* index index))
    (filter odd? (range 10)))
  (for [index (range 10) :when __]
    __))

For people experienced with Clojure, could you explain how they arrived at the solutions for this section? No matter how much I read about sequences, I just can't wrap my head around this section. Thanks!


Solution

  • I am assuming that you understand map and filter functions and I guess they are also present in Ruby. Let me give you an example and probably that can help you understand for use in this case.

    (map <some function to map a value> 
      (filter <some function to return true OR false to filter values>
              <a sequence of values>))
    

    The above code does some filtering on a sequence of values using filter and then map each value of the filtered sequence to some other value using map function.

    for basically allows you do same thing as shown below

    (for [index <a sequence of values> 
         :when <some expression to return true OR false by check index value>]
         (<some expression to map a value i.e transform index to something else>))
    

    I hope the above example will allow you to be able to map how the map and filter code can be expressed using for