为什么concat不在这里生效?

时间:2015-04-01 21:09:02

标签: clojure

以下是代码:

(def city-nodes (atom nil))
(def city-edges (atom nil))

(def player-pos (ref nil))
(def visited-nodes (ref #{}))
(def player-status (atom :in-progress))

(def ^:dynamic *node-num* 8)
(def ^:dynamic *edge-num* 5)
(def ^:dynamic *worm-num* 3)
(def ^:dynamic *cop-odds* 4)

(defn filterb
  [pred coll]
  (let [rt (filter pred coll)]
    (if (empty? rt)
      nil
      rt)))

(defn all-nodes []
  (range 1 (inc *node-num*)))

(all-nodes)

(defn rand-node []
  (inc (rand-int *node-num*)))

(defn edge-pair [x y]
  (when-not (= x y)
    [[x y] [y x]]))

(defn sample-2diff-nodes []
  (let [[x y] [(rand-node) (rand-node)]]
    (if (= x y)
      (sample-2diff-nodes)
      [x y])))

(edge-pair 1 1)
(take 4 (repeatedly #(sample-2diff-nodes)))

(def ^:dynamic t-edges (take 4 (repeatedly #(sample-2diff-nodes))))

(defn make-edge-vec []
  (->> (repeatedly #(sample-2diff-nodes))
       (take *edge-num*)
       (apply concat)
       set
       vec))

(binding [t-edges (take 4 (repeatedly #(sample-2diff-nodes)))])
(prn t-edges)
(binding [t-edges (make-edge-vec)])
(prn t-edges)
(binding [t-edges (apply concat t-edges)])
(prn t-edges)

结果:

(binding [t-edges (take 4 (repeatedly #(sample-2diff-nodes)))])
(prn t-edges)
(binding [t-edges (make-edge-vec)])
(prn t-edges)
(binding [t-edges (apply concat t-edges)])
(prn t-edges)

([6 1] [1 2] [5 2] [3 1])
([6 1] [1 2] [5 2] [3 1])
([6 1] [1 2] [5 2] [3 1])
nil

我是最后一个prn命令,我期待(6 1 1 2 5 2 3 1)。

1 个答案:

答案 0 :(得分:2)

绑定调用的结束)位于错误的位置:

(binding [t-edges (apply concat t-edges)])
(prn t-edges)

应该是:

(binding [t-edges (apply concat t-edges)]
  (prn t-edges))

虽然在这种情况下你几乎肯定想要使用let表达式