Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

idiom for padding sequences

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.

like image 938
Jegschemesch Avatar asked Dec 03 '14 01:12

Jegschemesch


1 Answers

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)
like image 182
Arthur Ulfeldt Avatar answered Oct 03 '22 14:10

Arthur Ulfeldt