0

New to Clojure so I've been going through 4Clojure's questions to get familiar with the core library before jumping on a project and have ran into this question:

// Write a function which reverses a sequence.
(= (__ [1 2 3 4 5]) [5 4 3 2 1])

This is just one of the test-cases but here is what I had come up with:

(fn [x my-seq]
  (if (empty? my-seq)
    x
    (do 
      (into x (take-last 1 my-seq))
      (recur x (into [] (drop-last my-seq)))))) []

I was getting an empty vector [ ] after executing this code in a repl so I modified the code like so:

(fn [x my-seq]
  (if (empty? my-seq)
    x
    (recur (into x (take-last 1 my-seq)) (into [] (drop-last my-seq))))) []

Question is why was my previous code not working? To me it seems logically equivalent, the modified code just seems cleaner where it avoids the do form. Again I'm new to Clojure so i'm not entirely familiar with the do and recur forms.

1 Answer 1

1

(into x (take-last 1 my-seq)) is the problem. Note that you cannot change x. (into x ...) creates a new vector and returns it.

However the return values of every statement inside (do ...) except for the last one are dropped. You are recurring with the original - empty - x.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh okay this is where the immutability comes in.. thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.