试图了解Haskell的=>与定义类型 [英] Trying to understand Haskell's => vs defining the types
问题描述
在Haskell中,为什么要定义具有类型约束的函数:
In Haskell, why would you define a function with a type constraint:
ghci> :t (==)
(==) :: (Eq a) => a -> a -> Bool
而不是定义它的类型是:
Rather than defining it so it's type was:
ghci> :t (==)
(==) :: Eq -> Eq -> Bool
推荐答案
您不会执行第二个版本,因为会遇到编译错误. Eq
不是类型,它是类型类.您不能在需要类型的地方使用类型类.
You wouldn't do the second version because you'd get a compile error. Eq
is not a type, it's a typeclass. You can't use a typeclass in places where a type is required.
如果您确实定义了自己的类型MyEq
,然后定义了类型为MyEq -> MyEq -> Bool
的函数==
,则表达式"hello" == "hello"
将无效,因为"hello"
是String类型而不是type类型的值MyEq.由于haskell中没有子类型,因此不能同时将String和MyEq类型的值赋值.
If you did define your own type MyEq
and then define a function ==
with the type MyEq -> MyEq -> Bool
, the expression "hello" == "hello"
would be invalid because "hello"
is a value of type String and not of type MyEq. Since there is no subtyping in haskell a value couldn't be of type String and of type MyEq at the same time.
因此,如果要定义一个可以接受满足特定条件的不同类型的值的函数,则需要类型类.
So if you want to define a function that can accept values of different types which meet certain conditions, you need type classes.
这篇关于试图了解Haskell的=>与定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!