gpt4 book ai didi

clojure - 方案-> Clojure : multimethods with predicates in the methods?

转载 作者:行者123 更新时间:2023-12-04 02:25:26 25 4
gpt4 key购买 nike

我正在将一些 Scheme 代码转换为 Clojure。最初使用的调度模式与多方法非常相似,但对匹配谓词采用了倒置的方法。例如,有一个通用函数“assign-operations”。目前,精确的实现细节并不太重要,但请注意它可以采用参数谓词列表。

(define (assign-operation operator handler . argument-predicates)
(let ((record
(let ((record (get-operator-record operator))
(arity (length argument-predicates)))
(if record
(begin
(if (not (fix:= arity (operator-record-arity record)))
(error "Incorrect operator arity:" operator))
record)
(let ((record (make-operator-record arity)))
(hash-table/put! *generic-operator-table* operator record)
record)))))
(set-operator-record-tree! record
(bind-in-tree argument-predicates
handler
(operator-record-tree record)))))

分派(dispatch)的函数提供这些谓词,函数的元数中的每个参数一个。
(assign-operation 'merge
(lambda (content increment) content)
any? nothing?)

(assign-operation 'merge
(lambda (content increment) increment)
nothing? any?)

(assign-operation 'merge
(lambda (content increment)
(let ((new-range (intersect-intervals content increment)))
(cond ((interval-equal? new-range content) content)
((interval-equal? new-range increment) increment)
((empty-interval? new-range) the-contradiction)
(else new-range))))
interval? interval?)

稍后,当调用通用函数“merge”时,会询问每个处理程序是否适用于操作数。

据我了解多方法,调度函数是在一组实现中定义的,根据 dispatch-fn 的返回值调度到特定的方法。在上面的 Scheme 中,新的赋值操作函数可以任意定义谓词。

Clojure 中的等价的惯用构造是什么?

编辑:上面的代码来自 "The Art of the Propagator" , 阿列克谢·拉杜尔和杰拉尔德·苏斯曼。

最佳答案

您可以使用 Clojure 的多方法相当容易地做到这一点——诀窍是创建一个分派(dispatch)函数来区分不同的谓词集。

最简单的方法可能是维护一个“复合谓词”向量,将所有单个谓词应用于完整参数列表,并使用该向量的索引作为调度值:

(def pred-list (ref []))

(defn dispatch-function [& args]
(loop [i 0]
(cond
(>= i (count @pred-list)) (throw (Error. "No matching function!"))
(apply (@pred-list i) args) i
:else (recur (inc i)))))

(defmulti handler dispatch-function)

(defn assign-operation [function & preds]
(dosync
(let [i (count @pred-list)]
(alter pred-list conj
(fn [& args] (every? identity (map #(%1 %2) preds args))))
(defmethod handler i [& args] (apply function args)))))

然后,您可以创建操作来处理您喜欢的任何谓词,如下所示:
(assign-operation (fn [x] (/ x 2)) even?)

(assign-operation (fn [x] (+ x 1)) odd?)

(take 15 (iterate handler 77))
=> (77 78 39 40 20 10 5 6 3 4 2 1 2 1 2)

关于clojure - 方案-> Clojure : multimethods with predicates in the methods?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7622269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com