80 days ago · 6 min read1286 words · Tech · hide · Fediverse post

Typeclasses are an overloading mechanism that allows compile time or runtime polymorphism. A typeclass method call like m a b ... (or a.m(b, ...) in Rust) resolves to a concrete method based on the type arguments passed to the method. class ToString t where toString :: t -> String instance ToString Bool where toString = undefined instance ToString Int where toString = undefined f = toString (123 :: Int) g = toString True toString here is overloaded: the two calls to the same method actually call different concrete methods. These type arguments are commonly based on the arguments or the return value (which is inferred from the call site context). class Convertible a b where convert :: a -> b instance Convertible Int String where convert = show instance Convertible Int Bool where convert = (/= 0) f :: Bool f = convert (123 :: Int) -- actual method called depends on the return type When a typeclass type parameter is not used in a method signature, the compiler has no way of choosing the…

Commenting on Bubbles has been removed. Why? If you want to talk about this post, write to the author, use the comments on their blog if it has them, or reply with a "RE:" post on your own blog. Suggestions? feedback@bubbles.town