Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get tails of sequence clojure

I have sequence in clojure of theem

(1 2 3 4) 

how can I get all the tails of sequence like

((1 2 3 4) (2 3 4) (3 4) (4) ())
like image 986
hariszaman Avatar asked Oct 08 '14 21:10

hariszaman


3 Answers

Another way to get all tails is by using the reductions function.

user=> (def x '(1 2 3 4))
#'user/x
user=> (reductions (fn [s _] (rest s)) x x)
((1 2 3 4) (2 3 4) (3 4) (4) ())
user=> 
like image 105
ez121sl Avatar answered Oct 18 '22 18:10

ez121sl


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

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

However, I think in this case it would be cleaner to just write it with lazy-seq:

(defn tails [xs]
  (if-not (seq xs) '(())
    (cons xs (lazy-seq (tails (rest xs))))))
like image 38
DaoWen Avatar answered Oct 18 '22 17:10

DaoWen


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) ())
like image 1
user100464 Avatar answered Oct 18 '22 16:10

user100464