1

http://www.4clojure.com/problem/23: "Write a function which reverses a sequence"

One solution is (fn [x] (reduce conj () x)), which passes all the tests. However, I'm curious why that solution works for the first test:

(= (__ [1 2 3 4 5]) [5 4 3 2 1])

Inlining the function evaluates to true in the REPL:

(= ((fn [x] (reduce conj () x)) [1 2 3 4 5]) [5 4 3 2 1])
true

However, if I evaluate the first argument to the =, I get (5 4 3 2 1), and (= (5 4 3 2 1) [5 4 3 2 1]) throws a ClassCastException.

Why does the former work while the latter doesn't? It seems like they should be equivalent …

2 Answers 2

2

The problem is that your list literal (5 4 3 2 1) is being evaluated as a function call. To use it properly you need to quote it, like so:

(= '(5 4 3 2 1) [5 4 3 2 1]) ;; => true

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

Comments

1

another way to do it without reduce is to use into () as it works exatcly as your reduction. So when you fill the blank this way, it solves the task:

(= (into () [1 2 3 4 5]) [5 4 3 2 1]) ;; true
(= (into () (sorted-set 5 7 2 7)) '(7 5 2)) ;; true
(= (into () [[1 2][3 4][5 6]]) [[5 6][3 4][1 2]]) ;; true

1 Comment

Nice! Just getting started with Clojure, so I didn't know about into

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.