haskell - MaybeT 的 m 在类型签名中

标签 haskell monads monad-transformers

查看 MaybeT:

λ: import Monad.Trans
λ: import Monad.Trans.Maybe
λ: :t MaybeT
MaybeT :: m (Maybe a) -> MaybeT m a

MaybeT 的签名中,m 可以是任何更高级的类型,即 * -> * 吗?

我正在尝试学习 Monad Transformers,所以我很好奇为什么 m 没有 Monad 的约束。

最佳答案

引用Learn You A Haskell :

Another example of a parameterized type that we've already met is Map k v from Data.Map. The k is the type of the keys in a map and the v 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 the Ord 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 for Map 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 is toList, that just takes a mapping and converts it to an associative list. It's type signature is toList :: Map k a -> [(k, a)]. If Map k v had a type constraint in its data declaration, the type for toList would have to be toList :: 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 是不受约束的,但有一个隐含的假设,即 mMonad 的一个实例。事实上,如果 m 不是 Monad 的实例,那么您将无法使用 MaybeT m a 值做很多事情,因为大多数函数将要求 mMonad 的一个实例。

关于haskell - MaybeT 的 m 在类型签名中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814151/

相关文章:

haskell - 如何从 haskell 字节串中读取 24 位整数?

parsing - 使用 makeExprParser 具有歧义

haskell - 如何将 Reader Monad 与 (Int -> Int) 一起使用?

haskell - monad 变压器内 monad 的结果

haskell - 为什么Haskell类型系统无法捕获这一点?

haskell - 使用测试创建完整的 Haskell 堆栈

Haskell——Rand monad 中的计算超时

haskell - 如何在 Haskell 函数中将随机数用作 Double ?

loops - Haskell 的 EitherT 发生了什么?

Haskell:为什么这个 monad 转换是错误的?