3 ms·
My major question is: how do you write reusable code without type classes? It's not really possible, as far as I can tell.
by the_duke 10y ago
My major question is: how do you write reusable code without type classes?
It's not really possible, as far as I can tell.
- kod 10y agoAre you trying to say that in the 30 years of time between the discovery of Lisp and the discovery of typeclasses, no one wrote reusable code?
- thinkpad20 10y agoWell of course there are ways to write reusable code without type classes. But let's say for the sake of argument that that's really what you want. You can in fact implement ad-hoc polymorphism, or something very close to it, without type classes. Type classes can be seen as a way to implicitly add a set of values to scope, but this can be done explicitly by using a record type. Consider (I'm guessing at syntax, I don't know elm): -- Monoid as a record type type Monoid a = { empty: a, append: a -> a -> a } -- Using this to make a generic concatenator mconcat : Monoid a -> [a] -> a mconcat m = foldl m.append m.empty -- Instance of Monoid for strings MString : Monoid String MString = { empty = "", append = (++) } -- Instance for ints MInt : Monoid Int MInt = { empty = 0, append = (+) } -- Use the generic function unlines : [String] -> String unlines = mconcat MString . intercalate "\n" You'll note here that the actual function signature for mconcat looks almost exactly like its Haskell counterpart, just that the Monoid instance is a regular argument like any other. Of course the downside is that you have to pass in the instance argument to any "type class polymorphic" function, so you lose a bit of conciseness but not much in the way of expressiveness. And you actually gain a bit, because instances are explicit (for example, you could make an instance of Monoid Int which used 1 and (*) instead). I'm not sure if this pattern is used anywhere in extant Elm code, but this is a common way to implement type classes under the hood in languages that support them, and the approach seems doable in elm.
- leshow 10y agoI'd like to refer you to the article that was posted earlier today on exactly this technique in Elm: http://reasonablypolymorphic.com/blog/elm-is-wrong http://reasonablypolymorphic.com/blog/elm-is-wrong
- the_duke 10y agoI formulated it badly I guess. I knew it's possible, s we discussed in the "Elm is wrong" comment thread though, this technique get's awkward quickly.