Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write Ruby's each_cons in Clojure?

Tags:

ruby

clojure

How can I rewrite this Ruby code in Clojure?

seq = [1, 2, 3, 4, 5].each_cons(2) 
#=> lazy Enumerable of pairs
seq.to_a
=> [[1, 2], [2, 3], [3, 4], [4, 5]]

Clojure:

(??? 2 [1 2 3 4 5])
;=> lazy seq of [1 2] [2 3] [3 4] [4 5]
like image 768
DNNX Avatar asked Aug 31 '13 19:08

DNNX


1 Answers

What you are asking for is called sliding window over a lazy sequence.This way you can achieve that

user=> (partition 2 1 [1 2 3 4 5])
((1 2) (2 3) (3 4) (4 5))
like image 51
Srinivas Reddy Thatiparthy Avatar answered Sep 23 '22 11:09

Srinivas Reddy Thatiparthy