gpt4 book ai didi

Clojure 多方法调度问题

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

我有这两个来源:

(ns odo.IComplex)
(gen-interface
:name odo.IComplex
:methods [
[getReal [] Double]
[getImag [] Double]
[getAbs [] Double]
[getArg [] Double]

[setReal [Double] void]
[setImag [Double] void]
[setAbs [Double] void]
[setArg [Double] void]])

(defprotocol PolarComplex
(abs [this] [this value])
(arg [this] [this value]))

(defmulti polar-complex (fn([record abs arg] (class record))))


(ns odo.Complex
(:gen-class
:init init
:state state
:implements [odo.IComplex])
(:use odo.IComplex))

(defrecord State [^Double imag ^Double real]
Object (toString [self]
(str real (if (>= imag 0) " + " " - " ) (Math/abs imag) "j"
" : " (abs self) " * exp[ " (arg self) " ]"))

PolarComplex (abs [self] (Math/sqrt (+ (* real real) (* imag imag))))
(abs [self value] (polar-complex self value (arg self)))

(arg [self] (Math/atan2 real imag))
(arg [self value] (polar-complex self (abs self) value)))

(defmethod polar-complex PolarComplex [num abs arg]
(assoc num :real (* abs (Math/cos arg)) :imag (* abs (Math/sin arg))))

(defn -init [] [[] (atom (State. 0. 0.))])
(defn -getImag [self] (:imag @(.state self)))
(defn -getReal [self] (:real @(.state self)))
(defn -getAbs [self] (abs @(.state self)))
(defn -getArg [self] (arg @(.state self)))

(defn -setImag [self value] (swap! (.state self) assoc :imag value))
(defn -setReal [self value] (swap! (.state self) assoc :real value))
(defn -setAbs [self value] (swap! (.state self) abs value))
(defn -setArg [self value] (swap! (.state self) arg value))

(defn -toString [self] (str @(.state self)))

我确信 (isa? odo.Complex.State odo.IComplex.PolarComplex)true
但是当我执行
(doto (odo.Complex.)
(.setArg (/ Math/PI 4.)) (.setAbs (Math/sqrt 2)) (println) )

我得到

java.lang.IllegalArgumentException: No method in multimethod 'polar-complex' for dispatch value: class odo.Complex.State



你能告诉我为什么吗?

最佳答案

我发现在其定义 var PolarComplex 的上下文中绑定(bind)到包含协议(protocol)信息的映射,而不是类。所以多方法的正确实现将是

(defmethod polar-complex (:on-interface PolarComplex) [num abs arg]
(assoc num :real (* abs (Math/cos arg)) :imag (* abs (Math/sin arg))))

或者
(defmethod polar-complex odo.IComplex.PolarComplex [num abs arg]
(assoc num :real (* abs (Math/cos arg)) :imag (* abs (Math/sin arg))))

关于Clojure 多方法调度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4233643/

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