In chapter 15 of Real World Haskell, a type class is defined:
class (Monad m) => MonadSupply s m | m -> s where
A couple paragraphs later, it says that >>= and return don't need to be defined because of the context. But there's no further explanation of what it means by context.
How does the compiler know MonadSupply is an instance of Monad if only 'm' is an instance of Monad?
What's a typeclass in Haskell? A typeclass defines a set of methods that is shared across multiple types. For a type to belong to a typeclass, it needs to implement the methods of that typeclass. These implementations are ad-hoc: methods can have different implementations for different types.
In Haskell, every statement is considered as a mathematical expression and the category of this expression is called as a Type. You can say that "Type" is the data type of the expression used at compile time. To learn more about the Type, we will use the ":t" command.
The shows functions return a function that prepends the output String to an existing String . This allows constant-time concatenation of results using function composition.
The "context" is just the part between class
and =>
, which in this case is the constraint Monad m
. And it's not so much that it "knows", more that it enforces it--writing an instance of MonadSupply
for a type m
that doesn't also have a Monad
instance will produce a compiler error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With