gpt4 book ai didi

haskell - MaybeT 的 m 在类型签名中

转载 作者:行者123 更新时间:2023-12-02 06:32:01 25 4
gpt4 key购买 nike

查看 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com