我正在寻找一种惯用的方法来获取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)
?
更新
我可能让它变得太复杂了,我认为这是上面更具功能性的实现 - 没有全局变量,没有变形,也没有动态范围:
(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 ))))
此版本更短,更简单,读取更好。所以我想我不需要动态范围,至少现在还没有。
后记
上面的更新中的“每次评估每次”方法都证明是有问题的,我无法弄清楚如何将所有条件测试实现为多方法调度(尽管我认为应该可行)。 / p>
所以我最终得到了一个宏,将表扩展为函数和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(代码作为数据,数据作为代码),两者都是正常的功能。 / p>
关于原始问题 - 如何在Clojure中进行动态范围设计 - 我认为答案变成了惯用的Clojure方法是找到一个不需要它的重构。
答案 0 :(得分:7)
您解决问题的方法似乎不太实用,而且您经常使用eval
;这闻起来很糟糕。
为什么不使用适当的函数代替使用传递给eval
的代码片段?如果所有模式都需要修改所需的变量,则可以直接将它们作为参数传递;如果不是,您可以将绑定作为地图传递。
答案 1 :(得分:6)
您的代码看起来比您需要的更难。我认为你真正想要的是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})
所有非常简洁和功能,不需要全局或甚至是attr-table。
USER =&GT; (html-attr:链接“a”“http://foo.com”) {:href“http://foo.com}
它并没有完全按照你的要求做一些修改,而是它。