I wrote this function that does this (easier to show than explain):
(split 2 (list 1 2 3 4 5 6))
=> ((1 2) (2 3) (3 4) (4 5) (5 6))
(defn split [n xs]
(if (> (count xs) (dec n))
(cons (take n xs) (split n (rest xs)))
'()))
I understand that in Clojure the list is not the only first class data structure. Would it make sense to write this data structure-agnostic? And regardless, is my implementation the most efficient and if not, how would I make it more efficient and/or idiomatic?
Thanks!
You can use the built in partition function,
(partition 2 1 (list 1 2 3 4 5 6))
=> ((1 2) (2 3) (3 4) (4 5) (5 6))
works for any sequence.
clojure.core/partition
([n coll] [n step coll] [n step pad coll])
Returns a lazy sequence of lists of n items each, at offsets step
apart. If step is not supplied, defaults to n, i.e. the partitions
do not overlap. If a pad collection is supplied, use its elements as
necessary to complete last partition upto n items. In case there are
not enough padding elements, return a partition with less than n items.
No need to write your own implementation. Clojure provides partition, which is lazy. Also no need to use list, if you use just Number literals:
(partition 2 '(1 2 3 4 5 6))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With