什么是实物签名约束 [英] What is Constraint in kind signature
问题描述
如果我检查Maybe
的kind
,我会得到:
If I inspect the kind
of Maybe
I get this:
λ> :k Maybe
Maybe :: * -> *
现在,如果我检查Monad
的种类,我会得到:
Now, if I inspect the kind of Monad
I get this:
λ> :k Monad
Monad :: (* -> *) -> Constraint
那里的Constraint
是什么,为什么需要它?为什么不只是这个* -> *
?
What is Constraint
there and why it is needed ? Why not just this * -> *
?
推荐答案
与Maybe
不同,Monad
不是 type ;这是一个 typeclass .
Unlike Maybe
, Monad
is not a type; it is a typeclass.
其他类型类也是如此:
Num :: * -> Constraint
Functor :: (* -> *) -> Constraint
Bifunctor :: (* -> * -> *) -> Constraint
其中*
代表具体类型(例如Bool
或Int
),->
代表种类更高的类型(例如Maybe
),而Constraint
代表类型约束的概念.这就是为什么:
Where *
represents concrete types (such as Bool
or Int
), ->
represent higher-kinded types (such as Maybe
), and Constraint
represents the idea of a type constraint. This is why:
我们知道我们不能像这样签名:
As we know we can't make a signature like this:
return :: a -> Monad a -- This is nonsense!
因为Monad
应该用作约束,也就是说,这必须是一个单子才能工作":
Because Monad
should be used as a constraint, to say that, 'this must be a monad to work':
return :: (Monad m) => a -> m a
之所以这样做,是因为我们知道return
不能在任何旧类型m
上运行,因此我们以名称Monad
为不同类型定义了return
的行为.换句话说,没有一个可以被称为Monad的事物,只有一个可以被称为Monadic的行为.
We do this because we know that return
can't work on any old type m
, so we define the behaviour of return
for different types under the name Monad
. In other words, there is no single thing that can be called a Monad, but only behaviour that can be called Monadic.
由于这个原因,我们创建了这个类型约束,说我们必须预先定义一个Monad才能使用此功能.这就是为什么Monad
是(* -> *) -> Constraint
的原因-它本身不是类型!
For this reason, we have created this type constraint, saying that we must have pre-defined something as a Monad to use this function. This is why the kind of Monad
is (* -> *) -> Constraint
- it itself is not a type!
Maybe
是Monad
的实例.这意味着有人在某处写过:
Maybe
is an instance of Monad
. This means that somewhere, someone has written:
instance Monad Maybe where
(>>=) = ... -- etc
...并定义Maybe
应如何表现为Monad.这就是为什么我们可以将Maybe
与具有前缀约束Monad m => ...
的函数或类型一起使用的原因.本质上,这是定义Monad
施加的约束的地方.
...and defined how Maybe
should behave as a Monad. This is why we can use Maybe
with functions or types that have the prefix constraint Monad m => ...
. This is essentially where one defines the constraint applied by Monad
.
这篇关于什么是实物签名约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!