动态var的Clojure绑定无法按预期工作 [英] Clojure binding of dynamic var not working as expected

查看:52
本文介绍了动态var的Clojure绑定无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,在动态var上设置新绑定会影响该绑定中调用的所有函数,以及从这些函数调用的所有函数。

From what I understand, setting a new binding on a dynamic var affects all functions called within that binding, and all functions called from those functions.

为什么绑定似乎在下面的第一个示例中丢失了?

Why does the binding appear to be lost in the first example below?

(def ^:dynamic *out-dir* "/home/user")

(binding [*out-dir* "/home/dave"] (map #(str *out-dir* %) [1 2 3]))
; gives:    ("/home/user1" "/home/user2" "/home/user3")
; expected: ("/home/dave1" "/home/dave2" "/home/dave3")

(binding [*out-dir* "/home/dave"] (conj (map #(str *out-dir* %) [1 2 3]) *out-dir*))
; gives: ("/home/dave" "/home/dave1" "/home/dave2" "/home/dave3")


推荐答案

这是由懒惰引起的- map 返回一个懒惰序列,该序列在绑定内定义但已评估外。您需要从内部强制执行评估:

This is caused by lazyness - map returns a lazy sequence which is defined inside the binding but is evaluated outside. You need to force the evaluation from inside:

(binding [*out-dir* "/home/dave"] 
  (doall (map #(str *out-dir* %) [1 2 3])))

这篇关于动态var的Clojure绑定无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆