查看 MaybeT
:
λ: import Monad.Trans
λ: import Monad.Trans.Maybe
λ: :t MaybeT
MaybeT :: m (Maybe a) -> MaybeT m a
在 MaybeT
的签名中,m
可以是任何更高级的类型,即 * -> *
吗?
我正在尝试学习 Monad Transformers,所以我很好奇为什么 m
没有 Monad
的约束。
最佳答案
Another example of a parameterized type that we've already met is
Map k v
fromData.Map
. Thek
is the type of the keys in a map and thev
is the type of the values. This is a good example of where type parameters are very useful. Having maps parameterized enables us to have mappings from any type to any other type, as long as the type of the key is part of theOrd
type class. If we were defining a mapping type, we could add a type class constraint in the data declaration:data (Ord k) => Map k v = ...
However, it is a very strong convention in Haskell to never add type class constraints in data declarations. Why? Well, because we don't benefit a lot, but we end up writing more class constraints, even when we don't need them. If we put or don't put the
Ord k
constraint in the data declaration forMap k v
, we're going to have to put the constraint into functions that assume the keys in a map can be ordered. But if we don't put the constraint in the data declaration, we don't have to put(Ord k) =>
in the type declarations of functions that don't care whether the keys can be ordered or not. An example of such a function istoList
, that just takes a mapping and converts it to an associative list. It's type signature istoList :: Map k a -> [(k, a)]
. IfMap k v
had a type constraint in its data declaration, the type fortoList
would have to betoList :: Ord k => Map k a -> [(k, a)]
, even though the function doesn't do any comparing of keys by order.So don't put type constraints into data declarations even if it seems to make sense, because you'll have to put them into the function type declarations either way.
我希望这能回答您的问题。虽然 MaybeT m a
中的 m
是不受约束的,但有一个隐含的假设,即 m
是 Monad
的一个实例。事实上,如果 m
不是 Monad
的实例,那么您将无法使用 MaybeT m a
值做很多事情,因为大多数函数将要求 m
是 Monad
的一个实例。
关于haskell - MaybeT 的 m 在类型签名中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814151/