Versatile into

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)

About these ads

8 Comments on “Versatile into”

  1. Concerned Netizen says:

    It doesn’t seem like you actually use ‘into’ in any of your code snippets.

  2. Fine, except ‘(b c d a) is not the reverse of ‘(a b c d).

    Why avoid recursion?

    • Octopusgrabbus says:

      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.

  3. Paul says:

    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.

    • Octopusgrabbus says:

      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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.