【问题标题】:Dynamic scoping in Clojure?Clojure中的动态范围?
【发布时间】:2010-05-30 23:58:10
【问题描述】:

我正在寻找一种惯用的方式来获取 Clojure 中的动态范围变量(或类似效果),以​​便在模板等中使用。

这是一个使用查找表将标签属性从某些非 HTML 格式转换为 HTML 的示例问题,其中表需要访问从其他地方提供的一组变量:

(def *attr-table* 
  ; Key: [attr-key tag-name] or [boolean-function]
  ; Value: [attr-key attr-value] (empty array to ignore)
  ; Context: Variables "tagname", "akey", "aval"
  '(
        ; translate :LINK attribute in <a> to :href
     [:LINK "a"]    [:href aval]
        ; translate :LINK attribute in <img> to :src
     [:LINK "img"]  [:src aval]
        ; throw exception if :LINK attribute in any other tag
     [:LINK]        (throw (RuntimeException. (str "No match for " tagname)))
     ; ... more rules
        ; ignore string keys, used for internal bookkeeping
     [(string? akey)] []  )) ; ignore

我希望能够评估规则(左侧)和结果(右侧),并且需要某种方法将变量置于评估表位置的范围内。

我还希望保持查找和评估逻辑独立于任何特定的表或变量集。

我想模板中也存在类似的问题(例如动态 HTML),您不希望每次有人在模板中放入新变量时都重写模板处理逻辑。

这是一种使用全局变量和绑定的方法。我已经包含了一些用于表查找的逻辑:

;; Generic code, works with any table on the same format.
(defn rule-match? [rule-val test-val]
  "true if a single rule matches a single argument value"
  (cond
    (not (coll? rule-val)) (= rule-val test-val) ; plain value
    (list? rule-val) (eval rule-val) ; function call
    :else false ))

(defn rule-lookup [test-val rule-table]
  "looks up rule match for test-val. Returns result or nil."
  (loop [rules (partition 2 rule-table)]
    (when-not (empty? rules)
      (let [[select result] (first rules)]
        (if (every? #(boolean %) (map rule-match? select test-val))
          (eval result) ; evaluate and return result
          (recur (rest rules)) )))))

;; Code specific to *attr-table*
(def tagname) ; need these globals for the binding in html-attr 
(def akey) 
(def aval) 

(defn html-attr [tagname h-attr]
  "converts to html attributes"
  (apply hash-map
    (flatten 
      (map (fn [[k v :as kv]]
             (binding [tagname tagname akey k aval v]
               (or (rule-lookup [k tagname] *attr-table*) kv)))
        h-attr ))))

;; Testing
(defn test-attr []
  "test conversion"
  (prn "a" (html-attr "a" {:LINK "www.google.com"
                           "internal" 42
                           :title "A link" }))
  (prn "img" (html-attr "img" {:LINK "logo.png" })))

user=> (test-attr)
"a" {:href "www.google.com", :title "A link"}
"img" {:src "logo.png"}

这很好,因为查找逻辑独立于表,因此它可以与其他表和不同的变量一起使用。 (当然,当我在一个巨大的条件下“手动”翻译时,通用表格方法的代码大小大约是我的四分之一。)

这不是很好,因为我需要将每个变量声明为全局变量才能使绑定起作用。

这是另一种使用“半宏”的方法,该函数具有带语法引用的返回值,不需要全局变量:

(defn attr-table [tagname akey aval]
  `(
     [:LINK "a"]   [:href ~aval]
     [:LINK "img"] [:src ~aval]
     [:LINK]       (throw (RuntimeException. (str "No match for " ~tagname)))
     ; ... more rules     
     [(string? ~akey)]        [] )))

只需要对其余代码进行几处更改:

In rule-match? The syntax-quoted function call is no longer a list:
- (list? rule-val) (eval rule-val) 
+ (seq? rule-val) (eval rule-val) 

In html-attr:
- (binding [tagname tagname akey k aval v]
- (or (rule-lookup [k tagname] *attr-table*) kv)))
+ (or (rule-lookup [k tagname] (attr-table tagname k v)) kv)))

没有全局变量我们得到相同的结果。 (并且没有动态范围。)

在没有 Clojure 的 binding 要求的全局变量的情况下,是否有其他替代方法可以传递在别处声明的变量绑定集?

有没有一种惯用的方法,比如Ruby's binding 还是Javascript's function.apply(context)

更新

我可能把它弄得太复杂了,我认为这是上面的一个更实用的实现——没有全局变量、没有 evals 和没有动态范围:

(defn attr-table [akey aval]
  (list
    [:LINK "a"]   [:href aval]
    [:LINK "img"] [:src aval]
    [:LINK]       [:error "No match"]
    [(string? akey)] [] ))

(defn match [rule test-key]
  ; returns rule if test-key matches rule key, nil otherwise.
  (when (every? #(boolean %)
          (map #(or (true? %1) (= %1 %2))
            (first rule) test-key))
    rule))

(defn lookup [key table]
  (let [[hkey hval] (some #(match % key)
                      (partition 2 table)) ]
    (if (= (first hval) :error)
      (let [msg (str (last hval) " at " (pr-str hkey) " for " (pr-str key))]
        (throw (RuntimeException. msg)))
      hval )))

(defn html-attr [tagname h-attr]
  (apply hash-map
    (flatten
      (map (fn [[k v :as kv]]
             (or
               (lookup [k tagname] (attr-table k v))
               kv ))
        h-attr ))))

这个版本更短、更简单、更好读。所以我想我不需要动态范围,至少现在不需要。

后记

我上面更新中的“每次都评估”方法被证明是有问题的,我无法弄清楚如何将所有条件测试实现为多方法调度(尽管我认为它应该是可能的)。

所以我最终得到了一个将表格扩展为函数和条件的宏。这保留了原始 eval 实现的灵活性,但更高效,需要更少的编码并且不需要动态范围:

(deftable html-attr [[akey tagname] aval]
   [:LINK ["a" "link"]] [:href aval]
   [:LINK "img"]        [:src aval]
   [:LINK]              [:ERROR "No match"]
   (string? akey)        [] ))))

扩展到

(defn html-attr [[akey tagname] aval]
  (cond
    (and 
      (= :LINK akey) 
      (in? ["a" "link"] tagname)) [:href aval]
    (and 
      (= :LINK akey) 
      (= "img" tagname))          [:src aval]
    (= :LINK akey) (let [msg__3235__auto__ (str "No match for "
                                             (pr-str [akey tagname])
                                             " at [:LINK]")]
                     (throw (RuntimeException. msg__3235__auto__)))
    (string? akey) []))

我不知道这是否特别实用,但肯定是 DSLish(制作一种微语言以简化重复性任务)和 Lispy(代码即数据,数据即代码),两者都与功能性正交。

关于最初的问题 - 如何在 Clojure 中进行动态范围界定 - 我想答案变成了惯用的 Clojure 方法是找到不需要它的重新表述。

【问题讨论】:

    标签: clojure


    【解决方案1】:

    您解决问题的方法似乎不是很实用,而且您使用eval 过于频繁;这闻起来像是糟糕的设计。

    不使用传递给eval 的代码的sn-ps,为什么不使用适当的函数呢?如果所有模式所需的变量都是固定的,则可以直接将它们作为参数传递;如果不是,您可以将绑定作为地图传递。

    【讨论】:

    • 我认为你说得有道理。我添加了一个更新版本,更好吗?
    • 我接受你的回答,因为它让我思考如何在没有 eval 的情况下做到这一点。我是函数式风格的新手,我的直觉是评估任何超出你绝对需要的东西是非常浪费的,但这可能是非函数式思维?
    【解决方案2】:

    您的代码看起来比需要的更难。我认为你真正想要的是 clojure 多方法。您可以使用它们更好地抽象您在 attr-table 中创建的调度表,并且不需要动态范围或全局变量来使其工作。

    ; helper macro for our dispatcher function
    (defmulti html-attr (fn [& args] (take (dec (count args)) args)))
    
    (defmethod html-attr [:LINK "a"]
      [attr tagname aval] {:href aval})
    
    (defmethod html-attr [:LINK "img"]
      [attr tagname aval] {:src aval})
    

    所有内容都非常简洁和实用,无需全局变量甚至属性表。

    USER=> (html-attr :LINK "a" "http://foo.com") {:href "http://foo.com}

    它并没有完全按照你的方式做,只是稍微修改一下就可以了。

    【讨论】:

    • 感谢您的提示。乍一看,这看起来比表格版本更多,因为“defmethod html-attr”加上参数列表的重复字符比实际规则更多,但我会看看它。无论如何,我们都同意我让它变得比需要的更难:)
    • j-g-faustus:看看clojure.template;正确使用,它将消除冗长。
    • Brian:谢谢,我去查一下。
    • Jeremy Wall:我接受了 Brian 的回答,因为它让我思考如何不使用 eval。但是多方法方法很好,我可能最终会在每次匹配有更多处理的情况下使用它,所以我宁愿避免在每次查找时运行所有计算。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多