47 minutes ago · 6 min read1286 words · Tech · hide · 0 comments

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…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.