1
votes

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

2 Answers

2
votes

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

1
votes

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