定义相互依赖的变量
我需要定义相互依赖的变量。我的意思是一个 var 包含例如一个带有另一个 var 的向量,反之亦然。下面的代码说明了这一点:
(declare a b)
(def a [1 b])
(def b [a 2])
但是加载此代码后我得到了这样的信息:
test=> (first a)
1
test=> (second a)
#<Unbound Unbound: #'test/b>
test=> (first b)
[1 #<Unbound Unbound: #'test/b>]
test=> (second b)
2
显然,这不是它应该如何工作的。 我知道打印这样的结构会导致堆栈溢出,但我不需要打印它。我该怎么做呢?
I need to define mutually-dependent vars. By this I mean that one var contains e.g. a vector with another var and vice versa. This is illustrated by the following code:
(declare a b)
(def a [1 b])
(def b [a 2])
But after loading this code I get this:
test=> (first a)
1
test=> (second a)
#<Unbound Unbound: #'test/b>
test=> (first b)
[1 #<Unbound Unbound: #'test/b>]
test=> (second b)
2
clearly, thats not how it should work.
I understand that printing such structure will give stack overflow, but I don't need to print it. How should I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以执行以下操作:
请注意,
#'
是用于引用 var 的读取器宏。我仍然不太确定你为什么要这样做......试图让变量像这样相互依赖对我来说似乎是一个非常糟糕的代码味道。无论您尝试做什么,实际上都可以通过不同的方法得到最好的解决。
编辑
额外的评论指出问题与不同类型的实体相互引用有关,我认为更好的方法是带有关键字的地图,例如
You can do the following:
Note that
#'
is a reader macro for referring to a var.I'm still not quite sure why you want to do this though..... trying to make vars mutually dependent like this seems like a pretty bad code smell to me. It's likely that whatever you are trying to do would actually be best solved by a different approach.
EDIT
With the extra comment stating that the problem is related to having different types of entities referring to each other, I think a better approach is a map with keywords, e.g.
首先,这听起来很像 XY 问题。
其次,如果不改变状态,就无法创建相互引用的数据结构。如果这就是您需要的数据结构(您可能不需要),那么请使用 clojure 设计良好的方法来表示。例如:
First, this smells very much like an XY problem.
Second, mutually referential data structures cannot be created without mutating state. If that's the data structure you need (and you probably don't), then use clojure's very well designed approach to state. For example:
惰性评估可能会有所帮助:
希望它有帮助,尽管我看不出它有什么用处。
Lazy evaluation might help:
Hope it helps, though I can't see how it's going to be useful.