idiom for padding sequences

clojure, sequences

Solution

Yes this is an idiomatic way of going about padding partitions of a sequence. In fact that code is very similar to part of the partition function in clojure.core the difference being that `partition` does not assume a single padding value and instead asks for a sequence:

core.clj:

([n step pad coll]
 (lazy-seq
    ...
    (list (take n (concat p pad))))))))

You can get the same results by passing a padding collection to partition:

user> (defn pad [n coll val]
        (take n (concat coll (repeat val))))
#'user/pad
user> (pad 10 [1 2 3] nil)
(1 2 3 nil nil nil nil nil nil nil)

user> (first (partition 10 10 (repeat nil) [1 2 3]))
(1 2 3 nil nil nil nil nil nil nil)

Problem

To pad out a sequence with some value, this is what I've come up with: ``` (defn pad [n coll val] (take n (concat coll (repeat val)))) (pad 10 [1 2 3] nil) ; (1 2 3 nil nil nil nil nil nil nil) ``` I'm curious if there's a shorter idiom that does this already and perhaps more efficiently.

Original source