Teddy
Teddy

Reputation: 4253

Trouble with using defmulti dispatch function

I have written this multi function in clojure.

(defmulti printlmt (fn [s] (> (count s) 10)))
(defmethod printlmt true [s] (println s))
(defmethod printlmt false [s] (println (take 10 s)))

I then try to execute it as below..

(printlmt "test")

But, I keep getting the following error.

IllegalArgumentException No method in multimethod 'printlmt' for dispatch value: 4  clojure.lang.MultiFn.getFn (MultiFn.java:156)

In my understanding the anonymous function should return a value of true. Why is the anonymous function returning 4?

If I call the dispatch function separately, like this

((fn [s] (> (count s) 0)) "test")

In this case it returns true!

Edit: I'm adding the terminal text which I have:

startingclojure.core=> (defmulti printlmt (fn [s] (> (count s) 10)))
nil
startingclojure.core=> (defmethod printlmt true [s] (println s))
#object[clojure.lang.MultiFn 0x3315fe88 "clojure.lang.MultiFn@3315fe88"]
startingclojure.core=> (defmethod printlmt false [s] (println (take 10 s)))
#object[clojure.lang.MultiFn 0x3315fe88 "clojure.lang.MultiFn@3315fe88"]
startingclojure.core=> 

startingclojure.core=> (printlmt "test")

IllegalArgumentException No method in multimethod 'printlmt' for dispatch value: 4  clojure.lang.MultiFn.getFn (MultiFn.java:156)
startingclojure.core=> 

Upvotes: 0

Views: 791

Answers (1)

Brandon Henry
Brandon Henry

Reputation: 3719

If you don't want to restart your repl for redefining a method, use remove-method

https://clojuredocs.org/clojure.core/remove-method

(remove-method printlmt true)

then redefine.

EDIT
You can use

(ns-unmap *ns* 'printlmt)

note: ns-unmap will require redefining all your methods as well.

Upvotes: 3

Related Questions