Haskell中的函数类型推断 [英] Type Inference in Haskell for functions

查看:86
本文介绍了Haskell中的函数类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在为Haskell做练习问题,问题之一是

I am doing practice problems for Haskell and one of the problems is

test3 x y = x (x y)

我必须找到其类型.

解决方案是

test3 :: (a -> a) -> a -> a

我不明白为什么解决方案中的变量都是a,而不是将x和y称为两个不同的变量,例如a和b.有人可以解释一下,还可以找到如何找到此问题的类型.

I am not understanding why the variables in the solution are all a's instead of referring to x and y as two different variables like a and b. Could someone explain that and also go through how to find the type of this problem.

推荐答案

实际上,这是一个非常有趣的练习.它不需要任何特定于Haskell的知识-它实际上只是基本逻辑.

This is quite an interesting exercise, actually. It doesn't require any Haskell-specific knowledge - it's really just basic logic.

test3 x y = x (x y)

首先要注意的是,test3接受2个参数(xy)并产生某种结果.因此类型必须为形式

The first thing to note is that test3 takes 2 arguments (the x and y) and produces some kind of result. So the type must be of the form

a -> b -> c

,仅需弄清楚abc是什么,或者至少它们之间存在什么关系.

and it only remains to figure out what a, b and c are, or at least what relations exist between them.

因此,让我们更详细地检查结果x (x y).它告诉我们x是可以将y作为参数的函数.我们已经说过y具有类型b(这是一个完全任意的名称,但是现在让我们继续使用它)-因此x必须是一个接受b并产生某种类型结果的函数.现在将其称为d类型.因此我们知道test3的类型为

So let's examine that result x (x y) in more detail. It tells us that x is a function which can take y as an argument. We have said that y has type b (which is a completely arbitrary name, but let's stick with it for now) - so x must be a function which takes a b and produces a result of some type. Let's call that type d for now. So we know that the type of test3 is of the form

(b -> d) -> b -> c

最后,再次从表达式x (x y)中,我们看到x必须采用x y-我们已将其分配为类型d-并返回结果.这个结果是test3的整体结果,我们选择了其类型为c.因此,在上面,我们已经将类型b -> d分配给它的x必须具有类型d -> c. b -> d等于d -> c的唯一方法是bcd都是同一类型. (因为函数的类型取决于它们的输入类型和结果类型.)因此,test3的整体类型必须为

Finally, again from the expression x (x y), we see that x must take the x y - which we've assigned the type d - and return a result. And this result is the overall result of test3, whose type we've chosen to call c. So, in the above, x - to which we've already assigned the type b -> d, must have type d -> c. The only way b -> d can be equal to d -> c is if b, c and d are all the same type. (Because the types of functions are determine by their input type and result type.) So the overall type of test3 must be of the form

(b -> b) -> b -> b

这正是您所知道的-最多将a重命名为b. (正如我所说,这些名称是任意的,因此不相关.)

Which is exactly what you've been told it is - up to a renaming of a to b. (The names are, as I said, arbitrary anyway - so it's not relevant.)

这篇关于Haskell中的函数类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆