【发布时间】: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