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 could do the same with concat.

On Dec 12, 3:10 pm, Mark Fredrickson <mark.m.fredrick...@gmail.com>
wrote:
> > 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-max '(2 4 12 3 4))
> 12
>
> For more complex data that you need to bring along, use a list or map.
>
> > 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]))
>
> This is still O(n) - though it needs to iterate the vector twice. The  
> second version shows off Clojure's nice improvement to reduce (vis-a-
> vis fold in Scheme): grabbing the first item from the head of the list/
> vec/seq. The down side is I can't write multi-sequence reduce calls  
> like Scheme, but c'est la vie.
>
> I could write O(n) versions with continuations in Scheme, but I think  
> loop/recur would be required in Clojure.
>
> Cheers,
> -Mark
--~--~---------~--~----~------------~-------~--~----~
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