Ashish Negi
Ashish Negi

Reputation: 5301

IllegalArgumentException: No single method in defprotocol

I am using defprotocol to achieve polymorphism. I have a simple logical-gates. forward and backward are two functions to be implemented by each of the gate.

Code:

;; a single unit has forward value and backward gradient.
(defrecord Unit 
    [value gradient])

(defrecord Gate
    [^:Unit input-a ^:Unit input-b])

(defprotocol GateOps
  (forward [this])
  (backward [this back-grad]))

(extend-protocol GateOps
  Unit
  (forward [this]
    (-> this :value))
  (backward [this back-grad]
    ({this back-grad})))

(defrecord MultiplyGate [input-a input-b]
  GateOps
  (forward [this]
    (* (forward (-> this :input-a)) (forward (:input-b this))))

  (backward [this back-grad]
    (let [val-a (forward (-> this :input-a))
          val-b (forward (-> this :input-b))
          input-a (:input-a this)
          input-b (:input-b this)]
      (merge-with + (backward input-a (* val-b back-grad))
                    (backward input-b (* val-a back-grad))))))

(defrecord AddGate [input-a input-b]
  GateOps
  (forward [this]
    (+ (forward (:input-a this)) (forward (:input-b this))))

  (backward [this back-grad]
    (let [val-a (forward (-> this :input-a))
          val-b (forward (-> this :input-b))
          input-a (:input-a this)
          input-b (:input-b this)]
      (merge-with + (backward input-a (* 1.0 back-grad))
                    (backward input-b (* 1.0 back-grad))))))


(defn sig [x]
  (/ 1 (+ 1 (Math/pow Math/E (- x)))))

(defrecord SigmoidGate [gate]
  GateOps
  (forward [this]
    (sig (forward (:gate this))))

  (backward [this back-grad]
    (let [s (forward this)
          ds (* s (- 1 s))]
      (backward (:gate this) ds))))

while forward is working fine, in backward i am getting exception :

user> (neurals.core/forward neurals.core/sigaxcby)
0.8807970779778823

user> (neurals.core/backward neurals.core/sigaxcby)
CompilerException java.lang.IllegalArgumentException: 
No single method: backward of interface: neurals.core.GateOps 
found for function: backward of protocol: GateOps, 
 compiling:(C:\xxyyzz\AppData\Local\Temp\form-init8132866244624247216.clj:1:1) 

user> 

Version info: Clojure 1.6.0

What am i doing wrong ?

Upvotes: 3

Views: 1244

Answers (1)

Ashish Negi
Ashish Negi

Reputation: 5301

This is weird as error-output does not have any correlation to the actual error : Arity error.

I should have given initial back-grad value to the backward function :

(neurals.core/backward neurals.core/sigaxcby 1.0) 

Upvotes: 3

Related Questions