reverse a sequence without reverse or rseq

1,534 views
Skip to first unread message

MarisO

unread,
Aug 8, 2011, 2:29:41 PM8/8/11
to Clojure
Do you know of any trick to reverse a sequence without reverse or
rseq ?

I wrote it like this:

((fn rev
([s] (rev '() s))
([r s] (if (seq s) (rev (cons (first s) r) (rest s)) r )) )
'[1 2 3 5] )


https://gist.github.com/1132357


I wonder if it can be written more shortly.

Mark Rathwell

unread,
Aug 8, 2011, 2:41:49 PM8/8/11
to clo...@googlegroups.com
user> (source reverse)

(defn reverse
  "Returns a seq of the items in coll in reverse order. Not lazy."
  {:added "1.0"}
  [coll]
    (reduce conj () coll))



--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@googlegroups.com
Note that posts from new members are moderated - please be patient with your first post.
To unsubscribe from this group, send email to
clojure+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Alan Malloy

unread,
Aug 8, 2011, 3:15:15 PM8/8/11
to Clojure
(into () [1 2 3 5])

Aaron Cohen

unread,
Aug 8, 2011, 3:17:00 PM8/8/11
to clo...@googlegroups.com
On Mon, Aug 8, 2011 at 2:29 PM, MarisO <maris.o...@gmail.com> wrote:
Another way to do it would be to follow the example of shuffle and defer to Java collections:

(defn reverse
  "Return coll, reversed"
  [coll]
  (let [al (java.util.ArrayList. coll)]
    (java.util.Collections/reverse al)
    (clojure.lang.RT/vector (.toArray al))))
Reply all
Reply to author
Forward
0 new messages