3 ms·
`defprotocol` and `extend-protocol` remind me of type classes and type class instances in Haskell. The latter provide the same kind of ad-hoc polymorphism - i.
by samstokes 16y ago
`defprotocol` and `extend-protocol` remind me of type classes and type class instances in Haskell. The latter provide the same kind of ad-hoc polymorphism - i.e. you can tell the compiler that your custom datatype implements a predefined protocol, and then code that talks to that protocol automatically works with your new datatype, in a statically type-safe and (I believe) efficient way.
For example, this (built-in) type class is similar to Java's `toString()`:
class Show a where
show :: a -> String
-- works with any instance of Show
showTwice :: (Show a) => a -> String
showTwice s = show s ++ show s
data Fruit = Orange | Apple
instance Show Fruit where
show Orange = "orange"
show Apple = "apple"
x = Orange
show x -- => "orangeorange"
Can anyone more familiar with Clojure (or Haskell for that matter) compare and contrast?
- samstokes 16y ago(Metacomment: huh, I thought `backticks` produced inline monospace, but apparently not. Is there a way to do that?)
- fogus 16y agoA popular meme that's going around the Clojure community right now is that Clojure's types and protocols are "dynamic type classes". Clojure's offering does not provide all of the same things that Haskell's type system gives -- like say, return type based method selection.