为什么不打印列表的行为就像列表理解?

时间:2012-06-26 15:19:45

标签: clojure list-comprehension

为什么我的println(示例的最后一行)不像列表理解?我正在尝试使用以下代码来解决Clojure中Project Euler问题#2的问题:

(def fibsq [0 1])

(defn second-to-last [sq]
  (nth sq (- (count sq) 2)))

(second-to-last fibsq)

(defn add-last-two [sq]
  (+ (last sq) (second-to-last sq)))

(defn add-to-fibsq [sq]
  (if (< (add-last-two sq) 100)
    (add-to-fibsq (conj sq (add-last-two sq)))
    sq))

;; putting it all together
(add-to-fibsq fibsq)

(println [x (add-to-fibsq fibsq) :when (even? x)])

我得到的输出如下:

  

(def || [0 1] || [0 1])

     

(定义倒数第二[|| [0 1 1 2 3 5 8 13 21 34 55 89] ||](第n || [0   1 1 2 3 5 8 13 21 34 55 89] || ( - (count || [0 1 1 2 3 5 8 13 21 34 55   89] ||)2)))

     

(倒数第二|| [0 1] ||)|| =&GT; 0 ||

     

(defn add-last-two [|| [0 1 1 2 3 5 8 13 21 34 55 89] ||](+(最后   || [0 1 1 2 3 5 8 13 21 34 55 89] ||)(倒数第二|| [0 1 1 2 3 5 8   13 21 34 55 89] ||)))

     

(defn add-to-fibsq [|| [0 1 1 2 3 5 8 13 21 34 55 89] ||](if(&lt;   (add-last-two || [0 1 1 2 3 5 8 13 21 34 55 89] ||)100)       (add-to-fibsq(conj || [0 1 1 2 3 5 8 13 21 34 55 89] ||(add-last-two || [0 1 1 2 3 5 8 13 21 34 55 89] || )))       || [0 1 1 2 3 5 8 13 21 34 55 89] ||))

     

;;把它们放在一起(add-to-fibsq || [0 1] ||)|| =&GT; [0 1 1 2 3 5   8 13 21 34 55 89] ||

     

(println [x(add-to-fibsq || [0 1] ||):何时(偶数?x)])|| =&GT;   java.lang.RuntimeException:无法解析符号:x   上下文,编译:(NO_SOURCE_PATH:19:2)||

这不是列表推导的工作原理吗?

1 个答案:

答案 0 :(得分:4)

Clojure没有像你试图在最后一行中使用的独立列表理解。你需要在最后一个表达式的开头调用for

(println (for [x (add-to-fibsq fibsq) :when (even? x)] x))

for函数将调用(add-to-fibsq fibsq)结果中每个条目的值绑定到x。在这种情况下,即使for也不仅仅需要

(println (filter even? (add-to-fibsq fibsq)))