Clojureのビデオを見る(3)
Classベースのオブジェクト指向とGeneric関数指向の違いについてRich Hickey氏の言及がある。 InfoQ: Rich Hickey on Clojure’s Features and Implementation
Q. Moving on to another feature that brings polymorphism to Clojure, multimethods to an object oriented programmer, how would you explain multimethods?
A. When you think about polymorphism, generally you are thinking about some Runtime dispatch. Something different happens at Runtime, depending on some characteristic of the object. It ends up that in object oriented programming languages like Java and C#, there is only one thing that can be a criteria for something different happening and that’s the class or type of the object. A general way of thinking about that is saying you have a method call and it involves an object and some arguments and the actual dispatch is going to differ, depending on the type of this.
You can generalize that and that was done in common Lisp to say it might be interesting to have things be polymorphic based upon more than just the first arguments. So, we are no longer considering the first arguments to be special and we’ll allow you to take some call and look at all the arguments and do something based upon all the arguments. There too, though, there are some things that are hardwired, for instance, in common Lisp you can only dispatch on either the type of arguments or their values. You can say “If it’s equal to this or if it’s of this type do this”, but you can do it for any or all the arguments. Again, we are talking about dispatch based upon some function of the arguments.
そうかそうか。メソッドディスパッチのレベルが違うのか。 JavaやC#のようなClassベースのオブジェクト指向の場合、メソッド呼び出しが実際にどの実体にディスパッチされるはClassかオブジェクトの型で決まる。 例)
Class::method1(a,b,c)
anObject.method1(a,b,c)
2番目の例について構文をLispっぽく記述したとしたら、こうなる。
(method1 anObject a b c)
ここで、method1が複数定義されている場合、Javaでは第一引数のanObjの型だけでどのメソッドが選択されるかが決まる。
一方、Common LispのようなGeneric関数指向では第一引数だけでなく全ての引数の型のマッチングで総合的に決まる。 メリットはJavaやC#のような強い依存度が無くなるということ。 うーんそういう視点は無かった。うんうん。 直接の関係は無いけど、戻り値に多値が使えるか使えないかで言語の適用範囲が広がるのと似たような感覚がある。