Versatile into
Posted: October 9, 2012 Filed under: Clojure | Tags: accumulator, Clojure, into, recursion 8 Comments »Given a Clojure list
(defn test-list '(a b c d))
and working through 99 Lisp problems and the particular problem of reversing a simple list, I’ve struggled to avoid using recursion and Clojure’s reverse function. I am working through those problems to obtain more familiarity and confidence in working with sequences.
The following sample will move one element to the end, but I want to keep going until the end of the list.
(defn rev-seq [s1] (concat (pop s1) (list (peek s1)))) (b c d a)
This
(repeat (count test-list) (rev-seq-elem test-list)) ((b c d a) (b c d a) (b c d a) (b c d a)) repl-test.core=>
did not help either.
And then, I remembered
into
which performs the accumulation and reversal all very nicely.
repl-test.core=> (into () test-list) (d c b a)
It doesn’t seem like you actually use ‘into’ in any of your code snippets.
Thanks. Fixed it.
Cool. I don’t think you need the anonymous function, though.
(into () ‘(a b c d))
Thanks.
Fine, except ‘(b c d a) is not the reverse of ‘(a b c d).
Why avoid recursion?
Thanks for finding I had deleted some text by mistake.
I was told in Google Clojure Group to avoid recursion because it is low-level.
While it’s true that in Clojure we try to use higher-level constructs when possible and only dip down to recursion when necessary, I think one of the main reasons that 99 problems are useful is that they teach you how to use recursion. So don’t be afraid to use it in solving these problems.
Thanks for your comment. I took the “recursion is low level” comments seriously, and avoiding it has steered me to understand the sequence functions better.