Type Classes in Elm

by: Ethan McCue

Conversation with somebody#0002

elm doesn't even have typeclasses apparently

Yeah, but you can do the pattern the same way scala does, just manually

so how does show work in elm

type alias ShowOps a =
    { show : a -> String }


show : ShowOps a -> a -> String
show ops a =
    ops.show a


stringShowOps : ShowOps String
stringShowOps =
    { show = identity }


intShowOps : ShowOps Int
intShowOps =
    { show = String.fromInt }


listShowOps : ShowOps a -> ShowOps (List a)
listShowOps elementShowOps =
    { show = \l -> "[ " ++ String.join ", " (List.map (show elementShowOps) l) ++ " ]" }


x : String
x =
    show (listShowOps intShowOps) [ 1, 2, 3 ]

Like this.

It's literally the same as scala except there are no implicit parameters - at which point you start to realize that maybe its not that special a pattern.

well

obviously.

it's the implicit parameters that is the special part

sure, but the point is if i want to take a parameter that is Show, I just need access to the functions

well... yes that's kinda how vtables work too?

Yep, it's all connected. You want "dynamic dispatch" in a strongly typed system with no interface polymorphism? Make a vtable, pass it around.


<- Index