简体   繁体   English

Clojure将序列与向量进行比较

[英]Clojure compare sequence to vector

http://www.4clojure.com/problem/23 : "Write a function which reverses a sequence" http://www.4clojure.com/problem/23 :“编写一个反转序列的函数”

One solution is (fn [x] (reduce conj () x)) , which passes all the tests. 一种解决方案是(fn [x] (reduce conj () x)) ,它通过了所有测试。 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: 内联函数在REPL中的计算结果为true

(= ((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 . 但是,如果我评估=的第一个参数,我得到(5 4 3 2 1) ,并且(= (5 4 3 2 1) [5 4 3 2 1])抛出一个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. 问题是您的列表文字(5 4 3 2 1)正在被评估为函数调用。 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. 另一种没有减少的方法就是使用into ()因为它可以作为你的减少而非常繁琐地工作。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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