2014-09-30 63 views
2

OtherWhat的更復雜版本(包裝)。它可以做什麼What但還有更多。我小心定義了2個名稱空間。Clojure:難以成功將協議應用於2種類型

(ns what) 

(defprotocol IWhatever 
    (whatever [this])) 

(deftype What [] 
    IWhatever 
    (whatever [this] 
      (str "whatever"))) 

(whatever (->What)) 

(ns other (:require what)) 

(deftype Other [] 
    what/IWhatever 
    (whatever [this] 
      (what/whatever (what/->What)))) 

(whatever (->Other)) ;bad line 

的錯誤是:

clojure.lang.Compiler$CompilerException: java.lang.RuntimeException: Unable to resolve symbol: whatever in this context, compiling:(C:\...) 

爲什麼不會在最後表達的決心?這就像名字找不到,但正如你所看到的,我在當前的名字空間下重新定義了它。

這是無稽之談,但我用問題的最簡單的例子來說明這一點。如果這是相關的,我在LightTable中運行它。

+2

當調用協議函數時,您需要使用符合條件的符號,即'(dict/get man:name)'而不是'(get man:name)'。 – Alex 2014-09-30 18:19:18

+0

它不會調用Dictionary版本,因爲Dictionary中的版本沒有實現。嘗試在repl中看到自己。 – soulcheck 2014-09-30 19:03:42

+2

@Mario我認爲你錯過了協議的要點。協議定義了一組多態函數。您可以調用協議函數,並根據第一個參數的類型進行調度。如果你不得不爲每個實現類型調用一個不同的函數,它將會失敗整個目的。 – Alex 2014-09-30 19:10:25

回答

1

使用定義協議的命名空間限定最後一行。我一直在考慮嘗試調用other命名空間中的whatever方法,因爲它在那裏定義。

(what/whatever (->Other)) 

感謝@soulcheck和其他花時間幫忙的人。