7

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]
fujy
  • 5,168
  • 5
  • 31
  • 50
DNNX
  • 6,215
  • 2
  • 27
  • 33
  • BTW, @fujy, when I added `ruby` tag in similar situation to this question http://stackoverflow.com/questions/18072261/how-to-rewrite-rubys-arrayx-in-clojure?rq=1 , @sawa removed it. I tend to agree with him. This is not a question about Ruby, it's a question about Clojure. – DNNX Aug 31 '13 at 19:52
  • 2
    Yes I agree with you that it's not a question about `ruby` . However, I think that the one who could answer should understand the `ruby` code. – fujy Aug 31 '13 at 19:55

1 Answers1

11

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))
  • 1
    I should have paid more attention when reading the partition function documentation. Thank you! – DNNX Aug 31 '13 at 19:44