Clojure - dispatch on return type? (As expressive as Haskell Typeclasses)

元气小坏坏 提交于 2019-12-05 02:42:56
J. Abrahamson

Let's imagine there were return type polymorphism in Clojure. That would allow us to write something like the Haskell class

class Default a where def :: a

In Haskell this works because it's a compile-time error to have a fragment like

def

as it's known to be ambiguous at compile time as to what that means. In a similar vein, if we were to write the Clojure fragment

(def)

it'd be impossible to know how to dispatch that call to the proper instance. To be more clear, the evaluation order for Clojure is that that in the fragment

(foo x y z)

the expressions x, y, and z get evaluated all prior to foo. In order for (def) to work it would need to somehow examine foo (and thus force its evaluation) in order to get information about how the return value of (def) will be used.

This could be done after a CPS transformation in which case (def) would be transformed into a function like (in Haskell type notation)

class Default a where def :: (a -> r) -> r

and now we see that we could examine the continuation function in order to learn information about the type of the parameter it expects and then dispatch off of that.

Finally, given enough macro magic this could be done... but likely for now less effort than implementing a Haskell-style type system atop Clojure. Typed Clojure could be a great model for this except it's been explicitly designed so that the semantics of Clojure cannot be affected by the inferred types. This is exactly what happens in return type polymorphism and so it's explicitly impossible in Typed Clojure.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!