Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure list manipulation

Tags:

clojure

I want to take a list and generate subsequences, in this manner:

(subs '(1 2 3))
; should evaluate to ((1) (1 2) (1 2 3) (2) (2 3) (3))

and yes, order matters. I might be missing something obvious, but I'm stuck. Bonus points for pretty solutions!

like image 437
Johanna Larsson Avatar asked Dec 01 '22 00:12

Johanna Larsson


1 Answers

Another take, a little shorter.

(defn subs4 [coll]
   (mapcat #(reverse (take (count %) (iterate butlast %)))
      (take (count coll) (iterate rest coll))))
like image 129
MisterMetaphor Avatar answered Jan 09 '23 03:01

MisterMetaphor