Friday 23 September 2011

Interpose into a sequence

The next task is to write a function that interposes a given value between elements of a sequence and returns the result.  For example we want the function f that does this:

(f 99 [1 2 3 4 5]))  => [1 99 2 99 3 99 4 99 5]

The built in function interpose does this already but the task is to write our own.

Well, the function repeat gives us a lazy infinite list of repeats of an element x:-

user=> (take 10 (repeat 99))
(99 99 99 99 99 99 99 99 99 99)


So we want to interleave this into our original sequence.  There is a function interleave that does this:-

user=> (interleave (repeat 99) [1 2 3 4 5])
(99 1 99 2 99 3 99 4 99 5)


But we do not want the first element, just the rest, so we say:-

user=> (defn f [x ys] (rest (interleave (repeat x) ys)))
#'user/f
user=> (f 99 [1 2 3 4 5])
(1 99 2 99 3 99 4 99 5)

No comments:

Post a Comment