我正在寻找一种惯用的方法来获取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"}
这很好,因为查找逻辑独立于表,因此可以与其他表和不同变量一起使用 . (当然,一般的表格方法大约是我在一个巨大的cond中“手动”进行翻译时所用代码大小的四分之一 . )
它不是那么好,我需要声明每个变量作为绑定工作的全局变量 .
这是另一种使用“半宏”的方法,一种带有语法引用返回值的函数,它不需要全局变量:
(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)?
Update
我可能使它太复杂了,这里我假设是一个更实用的上面的实现 - 没有全局,没有逃避和没有动态范围:
(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 ))))
此版本更短,更简单,读取更好 . 所以我想我不需要动态范围,至少现在还没有 .
Postscript
我上面的更新中的“每次评估每次”方法都证明是有问题的,我无法弄清楚如何将所有条件测试实现为多方法调度(尽管我认为应该可行) .
所以我最终得到了一个宏,将表扩展为函数和cond . 这保留了原始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方法是找到一个不需要它的重构 .
2 回答
你解决这个问题的方法看起来并不是很有用,你经常使用
eval
;这闻起来像糟糕的设计 .而不是使用传递给
eval
的代码片段,为什么不使用适当的函数呢?如果所有模式都需要修改所需的变量,则可以直接将它们作为参数传递;如果不是,您可以将绑定作为 Map 传递 .您的代码看起来像是在使它变得比它需要的更难 . 我认为你真正想要的是clojure多方法 . 您可以使用它们来更好地抽象您在attr-table中创建的调度表,并且不需要动态范围或全局变量来使其工作 .
所有非常简洁和功能,不需要全局甚至是attr-table .
USER =>(html-attr:LINK "a"“http://foo.com ") {:href " http://foo.com}
它并不能完全按照您的要求进行,只需稍加修改即可 .