Was Clojure influenced by ObjectiveC Protoc开发者_开发知识库ols? If no then how are they difference?
You might find these articles and links interesting:
- http://kirindave.tumblr.com/post/658770511/monkey-patching-gorilla-engineering-protocols-in - touches on objective-c a bit
- http://www.assembla.com/wiki/show/clojure/Protocols - Rich Hickey on motivation for protocols
- http://groups.google.com/group/clojure/msg/330c230e8dc857a9 - more Rich on protocols and other such things
They share the same name and the concepts are related - however Clojure protocols are more general and are designed to solve the "expression problem". This video is very interesting to watch.
Objective C protocols are more like Java/C# interfaces - they specify a set of methods that a concrete class can implement. However you have to provide these methods in the concrete class, which generally means in practice that you control the source code for the class you are extending.
Clojure protocols allow you define a set of functions that extend to handle any class in a polymorphic fashion, and you can provide the implementations separately even if you don't control the class you are extending.
An example of extending a Clojure protocol to the java.lang.String class for example (which you definitely don't control!) and also to the special value nil (i.e. a null value):
;; define a protocol with one function
(defprotocol FooProtocol
(foo [this]))
;; extend the protocol to String and nil
(extend-protocol FooProtocol
java.lang.String
(foo [some-string] (str "Called foo on String: " some-string))
nil
(foo [_] "Called foo on nil value"))
(foo "hello")
=> "Called foo on String: hello"
(foo nil)
=> "Called foo on nil value"
精彩评论