A very large chunk of iteration is done for the sake of producing a
new collection based on an existing collection, hence functional
constructs like list comprehensions and map. However, I'm not sure
about how to functionally handle cases of iteration which seem to
require:

1) keeping around values from previous iterations
2) producing a collection of more values than exist in the original
(or sometimes fewer values, though such cases usually require just
straight forward filtering)

For (1), it seems you generally resort to some kind of recursion with
loop/recur. Say we wish to find the max value in a list (without using
'max'):

 (def foo [35 -7 8 2 100 56])
 (loop [max (first foo)
           nums (rest foo)]
     (if (nil? nums)
         max
         (recur
            (if (> (first nums) max) (first nums) max)
            (rest nums))))

For (2), say I want to insert 3 before every item less than or equal
to 5 in a seq:

  (def bar [24 6 5 5 7 5 8 2])
  (defn prepend3 [s val] (if (<= val 5) (concat s [3 val]) (concat s
[val])))
  (loop [old (rest bar)
            new (prepend3 [] (first bar))]
      (if (nil? old)
          new
          (recur (rest old) (prepend3 new (first old)))))

  user=> (24 6 3 5 3 5 7 3 5 3 2)

Again, hardly elegant. Maybe there's a cleaner way to use loop in
these cases, or maybe I'm just forgetting some function(s) to use.
Hopefully someone can demonstrate better idioms to handle these common
cases.

--Brian Will
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to 
clojure+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to