Clojure 循环数据结构是否必须涉及像 ref 这样的结构? [英] Must Clojure circular data structures involve constructs like ref?
问题描述
今天我看到了一些关于打结和循环数据结构的参考资料.我一直在阅读一些答案,解决方案似乎涉及使用 ref 指向列表的头部.一个特定的 SO 问题 展示了一个 Haskell 示例,但我对 Haskell 不太了解,无法知道该示例是否使用了等效于 ref 的 Haskell.
Today I've seen some references to tying the knot and circular data structures. I've been out reading some answers, and the solutions seem to involve using a ref to point back to the head of the list. One particular SO question showed a Haskell example, but I don't know Haskell well enough to know if the example was using a the Haskell equivalent of a ref.
有没有办法在不使用 ref 或类似结构的情况下使 Clojure 数据结构循环?
Is there a way to make a Clojure data structure circular without using a ref or similar construct?
谢谢.
推荐答案
我直接将 Haskell 示例翻译成 Clojure:
I straightforwardly translated the Haskell example into Clojure:
user> (def alternates
(letfn [(x [] (lazy-seq (cons 0 (y))))
(y [] (lazy-seq (cons 1 (x))))]
(x)))
#'user/alternates
user> (take 7 alternates)
(0 1 0 1 0 1 0)
它按预期工作.但是我更喜欢 cycle
函数而不是使用 letfn
的相互递归函数:
It works as expected. However I prefer the cycle
function to mutually recursive functions using letfn
:
user> (take 7 (cycle [0 1]))
(0 1 0 1 0 1 0)
这篇关于Clojure 循环数据结构是否必须涉及像 ref 这样的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!