Looping idiom

3 views
Skip to first unread message

Brian Will

unread,
Sep 7, 2009, 9:51:50 PM9/7/09
to Clojure
Very basic question. What's the idiom for producing a new seq wherein
each val is based on pairs from an existing seq, e.g.:

; add together n0 n1, n1 n2, n2 n3, etc.
[1 2 3 4 5 6]
; giving...
[3 5 7 9 11]

The verbose way would be something like:

(loop [s origSeq n [ ])
(let [a (first origSeq)
b (second origSeq)]
(if (nil? b)
n
(recur (rest origSeq) (conj n (+ a b))))))

Brian Will

unread,
Sep 7, 2009, 9:53:27 PM9/7/09
to Clojure
should read:

(loop [s origSeq n [ ])
(let [a (first s
b (second s)]
(if (nil? b)
n
(recur (rest s) (conj n (+ a b))))))

Sean Devlin

unread,
Sep 7, 2009, 10:33:38 PM9/7/09
to Clojure
I'd use map, reduce, partial, and partition like so

user=>(map (partial reduce +) (partition 2 1 [1 2 3 4 5 6]))
(3 5 7 9 11)

Timothy Pratley

unread,
Sep 7, 2009, 11:39:25 PM9/7/09
to Clojure
Yet another way :)

user=> (map + (rest a) a)

songoku

unread,
Sep 8, 2009, 6:39:41 AM9/8/09
to Clojure
wow! i like your solution!

Sean Devlin

unread,
Sep 8, 2009, 10:22:36 AM9/8/09
to Clojure
Very very slick :)

Laurent PETIT

unread,
Sep 8, 2009, 10:29:23 AM9/8/09
to clo...@googlegroups.com


2009/9/8 Timothy Pratley <timothy...@gmail.com>


Yet another way :)

user=> (map + (rest a) a)
(3 5 7 9 11)

Haskell background ? :-)
 





atreyu

unread,
Sep 11, 2009, 1:23:44 AM9/11/09
to Clojure
uau cutting the Gordian knot
Reply all
Reply to author
Forward
0 new messages