Clojure 中的动态 let 列表解构
我有一个 let
语句,我想在其中动态解构列表。以下是我的解决方案:
symList ;; list of some Strings which will become the vector of Symbols to assign to
valList ;; list of some values, same length as symList
(let [(map read-string symList) valList]
...)
symList
的示例值为 ("pt1" "pt2")
,valList
的示例值为(1 2)
但是,这会产生一个异常,即第一部分是“不支持的绑定形式”。我怀疑我遗漏了一些有关语法引用的内容,或者这是不可能的。任何建议将不胜感激。
编辑:我只会知道这些值来自运行时,因此采用这种方法。其次,我需要能够稍后传递词法范围,因此使用 let
。
I have a let
statement in which I would like to dynamically destructure a list. The following is my solution:
symList ;; list of some Strings which will become the vector of Symbols to assign to
valList ;; list of some values, same length as symList
(let [(map read-string symList) valList]
...)
An example value of symList
would be ("pt1" "pt2")
and an example value of valList
would be (1 2)
However, this produces an exception that the first part is an "unsupported binding form". I suspect I am missing something regarding syntax-quoting, or that it's not possible. Any advice would be greatly appreciated.
EDIT: I will only know these values come run time, hence this approach. Secondly, I need to be able to pass the lexical scope later on, hence the use of let
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果 symList 和 valList 在编译时具有正确的值,那么您可以编写一个宏来执行此操作。如果它们仅在运行时已知,则您将必须使用/编写一个函数来为您进行解构,并将解构的结果作为某种数据结构返回。
在第二种情况下,对于像这样简单的事情,您可以使用
(zipmap symList valList)
来获取地图。If symList and valList have the correct value at compilation time, then you could write a macro to do this. If they are only known at runtime, you are going to have to use/write a function to do the destructuring for you and return the result of that destructuring as some data structure.
In the second case, for something simple like this, you can use
(zipmap symList valList)
to get a map.您收到的错误是因为您的 let 语句向后 (let [val SOURCE] STUFF)
The error you are getting is because your let statement was backwards (let [val SOURCE] STUFF)
也许 matchure 可以给你你想要的
maybe matchure can give you what you want
尽管我一直无法找到动态解构列表的方法,但对于那些有兴趣创建词法而不是动态作用域的值的人来说,我发现
intern
可以用于您需要的任何命名空间效果很好。Although I've been unable to find a way to dynamically destructure a list, for those of you who are interested in creating values that are lexically instead of dynamically scoped, I found that
intern
to whatever namespace you need works well.