简体   繁体   中英

Clojure compare sequence to vector

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 …

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM