Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Haskell infer correct type classes in MaybeT implementation?

How does Haskell know which is correct monad instance for each return expression?

newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }

instance Monad m => Monad (MaybeT m) where
    return  = MaybeT . return . return
like image 788
sevo Avatar asked Jul 20 '14 15:07

sevo


People also ask

How do you define a type class 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.

What is the difference between type and data in Haskell?

Type and data type refer to exactly the same concept. The Haskell keywords type and data are different, though: data allows you to introduce a new algebraic data type, while type just makes a type synonym. See the Haskell wiki for details.

What are types in Haskell?

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.

How do you create a data type in Haskell?

Making your own data type in HaskellNew data types are created via the data keyword. To create a Point data type, we need to provide a type constructor (the name of our type) and a data constructor (used to construct new instances of the type), followed by the types our type will contain.


1 Answers

It's actually unambiguous from the context.

Let's play the typechecker,

-- From the signature
MaybeT . return . return :: a -> MaybeT a 
-- From the type of MaybeT
return . return :: a -> m (Maybe a)
-- From the type of `.`
(return :: Maybe a -> m a) . (return :: a -> Maybe a)

And once we have the type of each return, the "instance selection algorithm" will correctly choose the first to use ms return and the second to be Maybe.

like image 167
Daniel Gratzer Avatar answered Nov 10 '22 01:11

Daniel Gratzer