Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most idiomatic Clojure way to write this?

Tags:

idioms

clojure

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!

like image 898
Tyler Avatar asked Jun 23 '10 08:06

Tyler


2 Answers

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.

like image 51
Hamza Yerlikaya Avatar answered Oct 13 '22 13:10

Hamza Yerlikaya


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)) 
like image 36
Jürgen Hötzel Avatar answered Oct 13 '22 13:10

Jürgen Hötzel