Re: iteration idioms

2008-12-13 Thread Stephen Parker
On 13 Dec 2008, at 12:39, Dave Newton wrote: > > --- On Sat, 12/13/08, Stephen Parker wrote: >> On 12 Dec 2008, at 23:10, Mark Fredrickson wrote: >>> [...] insert 3 before every item less than or equal to 5 in a seq: >> >> (def bar [24 6 5 5 7 5 8 2]) >> (insert-before-if #(<= 5 %) 3 bar) >> >> =>

Re: iteration idioms

2008-12-13 Thread Dave Newton
--- On Sat, 12/13/08, Stephen Parker wrote: > On 12 Dec 2008, at 23:10, Mark Fredrickson wrote: >> [...] insert 3 before every item less than or equal to 5 in a seq: > > (def bar [24 6 5 5 7 5 8 2]) > (insert-before-if #(<= 5 %) 3 bar) > > => (3 24 3 6 3 5 3 5 3 7 3 5 3 8 2) Er... Dave --~--

Re: iteration idioms

2008-12-13 Thread Stephen Parker
On 12 Dec 2008, at 23:10, Mark Fredrickson wrote: >> For (2), say I want to insert 3 before every item less than or equal >> to 5 in a seq: > > Again reduce to the rescue: > > (reduce into (map (fn [i] (if (<= i 5) [3 i] [i])) [24 6 5 5 7 5 8 > 2])) Could use mapcat: (def bar [24 6 5 5 7 5 8

Re: iteration idioms

2008-12-12 Thread Brian Will
Thanks, Mark. I don't suppose (reduce into ...) is a common enough idiom that it deserves its own function? Perhaps (into x) should do (reduce into x), e.g. (into [[3 5] [6 7]]) => [3 5 6 7]. This makes sense to me, but maybe it's too semantically different from (into x y). If not, though, you co

Re: iteration idioms

2008-12-12 Thread Mark Fredrickson
> > 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'): I can do this with reduce: user=> (defn my-max [lst] (reduce (fn [x a] (if (> x a) x a)) (first lst) (rest lst))) #'user/my-max user=> (my

iteration idioms

2008-12-12 Thread Brian Will
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 valu