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
Could use mapcat:
(def bar [24 6 5 5 7 5 8 2])
(defn insert-before-if [pred ins lst]
(mapcat #(if (pred %) [ins %] [%]) lst))
(insert-before-if #(<= 5 %) 3 bar)
=> (3 24 3 6 3 5 3 5 3 7 3 5 3 8 2)
stephen
Er...
Dave
Must have been asleep:
(def bar [24 6 5 5 7 5 8 2])
(defn insert-before-if [pred ins lst]
(mapcat #(if (pred %) [ins %] [%]) lst))
(insert-before-if #(<= % 5) 3 bar)
stephen