简体   繁体   English

与Haskell中的嵌套Lambda类型混淆

[英]Confused with nested lambda types in haskell

Just trying to see the types of some lambda expressions like this one: 只是尝试查看一些lambda表达式的类型,例如:

:t \x -> (\y -> x y)
\x -> (\y -> x y) :: (t1 -> t2) -> t1 -> t2

shouldn't the type here be t1->(t2->t1->t2) ? 这里的类型不应该是t1->(t2->t1->t2)吗?

Similarly 相似地

:t \x -> (\y -> (\k -> y (x k)))
\x -> (\y -> (\k -> y (x k)))
  :: (t1 -> t2) -> (t2 -> t3) -> t1 -> t3

Shouldn't the type be t1->(t2->(t3->t2)) ? 类型不应该是t1->(t2->(t3->t2))吗?

 :t \\x -> (\\y -> xy) \\x -> (\\y -> xy) :: (t1 -> t2) -> t1 -> t2 

shouldn't the type here be t1->(t2->t1->t2) ? 这里的类型不应该是t1->(t2-> t1-> t2)吗?

No, t1->(t2->t1->t2) is the same as t1->t2->t1->t2 which is the type of a three-arguments function (of type t1 , t2 , and t1 ) returning t2 . 不, t1->(t2->t1->t2)t1->t2->t1->t2相同,后者是返回t2的三参数函数(类型为t1t2t1 ) 。 However, there are only two lambdas, for the two arguments x and y . 但是,对于两个参数xy ,只有两个lambda。

The right type is instead 正确的类型是

typeOfX -> (typeofY -> typeOfResult)
\x ->      (\y ->      x y)

(By the way, none of the parentheses above are needed.) (顺便说一句,不需要上面的括号。)

What is typeOfResult ? 什么是typeOfResult Is is the type of xy , so it is the return type for x which must be a function. Is是xy的类型,因此它是x的返回类型,必须是一个函数。

In order for the code to type check, we must then have that typeOfX is a function type, say a -> b . 为了使代码能够进行类型检查,我们必须使typeOfX为函数类型,例如typeOfX a -> b In such case we can see that typeOfResult = b . 在这种情况下,我们可以看到typeOfResult = b Further, in xy we pass y to x , and this can type check only if typeOfY = a . 此外,在xy我们将y传递给x ,并且只有在typeOfY = a才可以输入check。

So, 所以,

typeOfX  -> typeofY -> typeOfResult
=
(a -> b) -> a       -> b

The compiler used names t1 and t2 , but this is the same type. 编译器使用名称t1t2 ,但这是相同的类型。

Parentheses here matter, since we must remember that x is a function a -> b . 这里的括号很重要,因为我们必须记住x是一个函数a -> b Without parentheses we would get a three-argument function, as explained above. 没有括号,我们将得到一个三参数函数,如上所述。

You can try to apply the same reasoning to the second example. 您可以尝试将相同的推理应用于第二个示例。 Start from typeOfX -> typeofY -> typeOfK -> TypeOfResult , and slowly discover what these types actually are. typeOfX -> typeofY -> typeOfK -> TypeOfResult ,然后慢慢发现这些类型实际上是什么。

The type of x in \\x -> \\y -> xy is t1 -> t2 , and it's the first argument. \\x -> \\y -> xyx的类型是t1 -> t2 ,它是第一个参数。 As the outermost lambda, it gets applied first, followed by y 作为最外层的lambda,首先应用它,然后是y

You could've written it as \\xy -> xy which is just function application in the natural order. 您可以将其编写为\\xy -> xy ,这只是自然顺序的函数应用程序。

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

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