How to get clojure sequence tails

I have a sequence in clojure ofem

(1 2 3 4) 

how can i get all the tails of a sequence like

 ((1 2 3 4) (2 3 4) (3 4) (4) ()) 
+6
source share
6 answers

Another way to get all the tails is with the reductions function.

 user=> (def x '(1 2 3 4)) #'user/x user=> (reductions (fn [s _] (rest s)) xx) ((1 2 3 4) (2 3 4) (3 4) (4) ()) user=> 
+13
source

If you want to do this with higher level functions, I think iterate will work well:

 (defn tails [xs] (concat (take-while seq (iterate rest xs)) '(())) 

However, I think in this case it would be easy to write it using lazy-seq :

 (defn tails [xs] (if-not (seq xs) '(()) (cons xs (lazy-seq (tails (rest xs)))))) 
+4
source

Here is one way.

 user=> (def x [1 2 3 4]) #'user/x user=> (map #(drop % x) (range (inc (count x)))) ((1 2 3 4) (2 3 4) (3 4) (4) ()) 
+1
source

One way to do this is

 (defn tails [coll] (take (inc (count coll)) (iterate rest coll))) 
+1
source
 (defn tails [s] (cons s (if-some [r (next s)] (lazy-seq (tails r)) '(())))) 
0
source

Yippee! One more:

 (defn tails [coll] (if-let [s (seq coll)] (cons coll (lazy-seq (tails (rest coll)))) '(()))) 

This is really what reductions does under the hood. The best answer, by the way, is ez121sl .

0
source

Source: https://habr.com/ru/post/976453/


All Articles