clojure - 使用循环并使用惰性序列重复

dag*_*da1 5 clojure lazy-evaluation

如果我从这样的函数返回一个lazy-seq:

(letfn [(permutations [s]
              (lazy-seq
               (if (seq (rest s))
                 (apply concat (for [x s]
                                 (map #(cons x %) (permutations (remove #{x} s)))))
                 [s])))])
Run Code Online (Sandbox Code Playgroud)

如果我使用下面的循环重复,是否会急切地评估列表?

(loop [perms (permutations chain)]
       (if (empty? perms)
         (prn "finised")
         (recur (rest perms))))
Run Code Online (Sandbox Code Playgroud)

如果热切评估,我可以使用loop..recur来懒散地循环从permutations函数返回的内容吗?

Mii*_*kka 6

循环复现代码懒惰地评估该列表.

你可以自己尝试一下.permutations每次通过添加println调用返回值时,让我们打印一些东西.

(defn permutations [s]
  (lazy-seq
   (if (seq (rest s))
     (apply concat (for [x s]
                     (map #(cons x %) (permutations (remove #{x} s)))))
     (do
       (println "returning a value")
       [s]))))
Run Code Online (Sandbox Code Playgroud)

使用时loop,让我们打印值,我们正在循环(prn (first perms).

(loop [perms (permutations [1 2 3])]
  (if (empty? perms)
    (prn "finised")
    (do
      (prn (first perms))
      (recur (rest perms)))))
Run Code Online (Sandbox Code Playgroud)

这是它打印的内容:

returning a value
(1 2 3)
returning a value
(1 3 2)
returning a value
(2 1 3)
returning a value
(2 3 1)
returning a value
(3 1 2)
returning a value
(3 2 1)
"finished"
Run Code Online (Sandbox Code Playgroud)

如您所见,"返回一个值"和值行是隔行扫描的.可以强制评估懒惰的seq doall.如果你循环(doall (permutations [1 2 3])),首先它打印所有"返回值"行,然后只打印值.