On Wed, Apr 22, 2009 at 4:57 PM, samppi <[email protected]> wrote:
>
> Let's say I have a sequence of integers:
> (def a (3 9 1 5 102 -322 ...))
>
> Is there a function for inserting an object—let's say :foo—after
> elements that fulfill a certain predicate?
> Furthermore, I mean inserting :foo after any block of elements that
> fulfill it:
>
> (mystery-function (partial > 6) a) ; -> (3 :foo 9 1 5 :foo 102
> -322 :foo ...)
>
> Is it possible to do this without a loop?
This depends on what you mean by "without a loop" I suppose. There
surely has to be a loop somewhere, doesn't there?
Although there's no explicit loop in Laurent's solution, there is a
(recursive) loop in the definition of partition-by.
I wasn't sure what you meant by "inserting :foo after any block of
elements that fulfill it", so this was my attempt at a solution:
(defn insert-right-if [ins coll f]
(cond (empty? coll) coll
(f (first coll))
(lazy-seq
(cons (first coll) (cons ins (insert-right-if ins (rest coll) f))))
:else (lazy-seq
(cons (first coll) (insert-right-if ins (rest coll) f)))))
This will insert ins after every element for which (f element) returns
true, i.e. not quite what you want.
Laurent's solution breaks with a large sequence:
user=> (take 10 (mystery-function (partial > 6) (iterate inc 0) :foo))
java.lang.OutOfMemoryError: Java heap space (NO_SOURCE_FILE:0)
user=> (nth (mystery-function (partial > 6) (iterate inc 0) :foo) 100000000)
java.lang.OutOfMemoryError: Java heap space (NO_SOURCE_FILE:0)
Mine (although it's not quite the right answer) handles this without
running out of memory:
user=> (nth (insert-right-if :foo (iterate inc 0) (partial > 6)) 100000000)
99999994
--
Michael Wood <[email protected]>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---