简体   繁体   English

咖喱(==)如何运作?

[英]How does curry (==) work?

I understand that: 我明白那个:

(==) :: Eq a => a -> a -> Bool (==):: Eq a => a - > a - > Bool

An example of application may be (==) 2 2, which result is True. 应用程序的示例可以是(==)2 2,结果为True。

and that: 然后:

uncurry (==) :: Eq b => (b, b) -> Bool. uncurry(==):: Eq b =>(b,b) - > Bool。

An example of application may be uncurry (==) (2, 2), which result is True. 应用程序的示例可能是uncurry(==)(2,2),结果为True。

But I don't understand and visualize an example why: 但我不明白并想象一个例子为什么:

curry (==) :: (Eq a, Eq b) => a -> b -> (a, b) -> Bool 咖喱(==)::(Eq a,Eq b)=> a - > b - >(a,b) - > Bool

Any help? 有帮助吗?

Thanks, 谢谢,
Sebastián 塞巴斯蒂安

== can be used on tuples, that is you can write (a1, b1) == (a2, b2) . ==可以在元组上使用,也就是你可以写(a1, b1) == (a2, b2)

In that case the type of == is specialized to (Eq a, Eq b) => (a, b) -> (a,b) -> Bool . 在这种情况下, ==的类型专门用于(Eq a, Eq b) => (a, b) -> (a,b) -> Bool

If you now apply curry to that type, you get (Eq a, Eq b) => a -> b -> (a, b) -> Bool . 如果您现在将curry应用于该类型,则得到(Eq a, Eq b) => a -> b -> (a, b) -> Bool

The definition of curry is: curry的定义是:

curry :: ((a, b) -> c) -> a -> b -> c
curry f = \x y -> f (x, y)

If we substitute that in: 如果我们用以下代替:

\x y z -> (curry (==) x y) z
\x y z -> ((==) (x, y)) z    -- Function application
\x y z -> (==) (x, y) z      -- Remove parentheses (function application is left associative in Haskell, so they are unnecessary here)
\x y z -> (x, y) == z        -- Convert to infix

We can tell right away that z must be some kind of tuple as well, or else this last line wouldn't type check since both arguments of == must have the same type. 我们可以立刻知道z必须是某种元组,否则最后一行不会进行类型检查,因为==两个参数必须具有相同的类型。

When we look at the definition of the tuple instance for Eq , we find 当我们查看Eq的元组实例的定义时,我们发现

instance (Eq a, Eq b) => Eq (a, b) where
  (x, y) == (x', y') = (x == x') && (y == y')

(This isn't spelled out in the source code of the standard library, it actually uses the "standalone deriving" mechanism to automatically derive the instance for the (Eq a, Eq b) => (a, b) type. This code is equivalent to what gets derived though.) (这不是在标准库的源代码中拼写出来的,它实际上使用“独立派生”机制来自动派生(Eq a, Eq b) => (a, b)类型的实例。相当于得到的东西。)

So, in this case, we can treat == as though it has the type 所以,在这种情况下,我们可以将==视为具有类型

(==) :: (Eq a, Eq b) => (a, b) -> (a, b) -> Bool

Both x and y must have types that are instances of Eq , but they don't need to be the same instance of Eq . xy必须具有Eq实例的类型,但它们不需要是Eq相同实例。 For example, what if we have 12 and "abc" ? 例如,如果我们有12"abc"怎么办? Those are two different types but we can still use our function, since they are both instances of Eq : (\\xyz -> (x, y) == z) (12, "abc") (30, "cd") (this expression type checks and evaluates to False ). 这是两种不同的类型,但我们仍然可以使用我们的函数,因为它们都是Eq实例: (\\xyz -> (x, y) == z) (12, "abc") (30, "cd") (此表达式类型检查并计算为False )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM