I’m a little bit confused about how Haskell dispatches to the correct function in a typeclass. Is this done implicitly, or does this have something to do with how Haskell infers the type of something? For instance, consider the following:
instance Monad Parser where
return a = Parser (\ cs -> [(a, cs)])
If I do something like:
return something >>= \x -> -- Returning a parser!
Does haskell guess which return to call using the right side of the bind? How does it know to call the Parser return as opposed to some other one?
Edit:
Okay, so this actually raises more questions for me. I get how Haskell could infer what “return” should be by solving type declarations. However, what about in the case of a totally ambiguous statement?
For instance, what if I open up the interpreter and enter return 1? How does it know which return to call then?
That’s correct — Haskell can dispatch on the return type. In fact, since Haskell is a functional language, there is no strict notion of a “return type”. For example, is
Intin(Bool -> Int) -> Stringa return type?So, how does this happen? First, Haskell infers the type for an expression. It has the form
where
Ctxis the context and has the form(Class1 vars1, Class2 vars2, ...).Now, in most cases (like in yours) all the type variables that occur in the context also occur in the type
t. Hence, once those variables are instantiated to concrete types, it’s possible to resolve overloaded methods.Specifically, in your case, Haskell knows that the bind operator
>>=has the typeSince the right operand has the type
Parser bfor someb, themvariable must beParser, soreturnhas typea -> Parser a.In some cases there might be variables in the context which do not occur in
t.E.g.
has the type
String, but to be evaluated it needs to choose some instance of bothReadandShowclasses.In that case it is either resolved using the defaulting mechanism, or an error is reported. In the latter case you can fix it by providing an explicit signature.