【问题标题】:Difference between binding and with-bindings绑定和绑定之间的区别
【发布时间】:2017-05-25 17:48:18
【问题描述】:

Clojure 函数bindingwith-bindings 有什么区别?它们似乎做同样的事情,但语法略有不同。

【问题讨论】:

    标签: multithreading syntax clojure


    【解决方案1】:
    当您需要动态选择要绑定的内容时,

    with-bindings 非常有用。这是一个有趣的例子,我们随机选择要绑定的内容:

    user> (def ^:dynamic a)
    #'user/a
    user> (def ^:dynamic b)
    #'user/b
    user> (binding [a 1
                    b 2]
            (+ a b))
    3
    user> (with-bindings (if (rand-nth [true false])
                           {#'a 1
                            #'b (rand-int 10)}
                           {#'a 1
                            #'b 2})
            (+ a b))
    3
    user> (with-bindings (if (rand-nth [true false])
                           {#'a 1
                            #'b (rand-int 10)}
                           {#'a 1
                            #'b 2})
            (+ a b))
    3
    user> (with-bindings (if (rand-nth [true false])
                           {#'a 1
                            #'b (rand-int 10)}
                           {#'a 1
                            #'b 2})
            (+ a b))
    1
    

    如果您尝试使用 bind 进行此操作,它会因为未将文字向量作为绑定形式传递而感到不安。

    user> (binding (if (rand-nth [true false])
                     {#'a 1
                      #'b (rand-int 10)}
                     {#'a 1
                      #'b 2})
            (+ a b))
    IllegalArgumentException binding requires a vector for its binding in user:138  clojure.core/binding (core.clj:1865)
    

    【讨论】:

    • 谢谢!我很困惑binding 的文档没有提到线程,而with-bindings 的文档却提到了线程。但是你的例子很清楚。
    【解决方案2】:

    其实也是一样的:

    (def ^:dynamic x 1)
    ;;=> #'user/x
    
    x
    ;;=> 1
    
    (with-bindings {#'x 2}
       x)
    ;;=> 2
    

    【讨论】:

      【解决方案3】:

      您可能会注意到输入参数的细微差别:binding 接受符号,而 with-bindings 接受变量。另外,如上所述,由于with-bindings 采用地图,您可以根据您的应用程序逻辑动态组合它。

      【讨论】:

        猜你喜欢
        • 2017-01-20
        • 2012-11-20
        • 2013-09-20
        • 1970-01-01
        • 1970-01-01
        • 2016-09-17
        • 2011-05-21
        • 1970-01-01
        • 2018-01-01
        相关资源
        最近更新 更多