如何确定Haskell函数的类型? [英] How do I determine type of Haskell functions?

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

问题描述

我正在为考试做准备,但是有些事情我听不懂.

I'm preparing for my exams but there is something I can't understand.

功能:

tw f x = f (f x)
f x y = (y, x)

我能够确定'f'的类型

I am able to determine the type of 'f' which is

f :: t1 -> t -> (t, t1)

但无法确定'tw'的类型.

but can't determine the type of 'tw'.

tw的假定类型:

tw :: (t -> t) -> t -> t

谢谢!

推荐答案

让我们分析函数 tw :

tw f x = f (f x)

tw f x 为参数.目前,我们对这些参数还不太了解,因此我们将这些类型指定为 f :: a x :: b .

tw takes as parameters f and x. At the moment we dot not know much about these parameters, so we will give these as types f :: a and x :: b.

现在,我们看到具有 f 函数和 x 参数的函数应用程序.因此,这意味着 f 是一个函数,该函数采用类型为 b (类型为 x 的值)的值,并返回某些内容.因此,我们指定 f 的类型为 f:b->.c ,我们引入了 c 一个新的类型变量.因此,我们知道 f x :: c .

Now we see a function application with f the function and x the parameter. This thus means that f is a function that takes a value of type b (the type of x), and returns something. We thus specify that f has as type f :: b -> c, with c a new type variable we introduce. We thus know that f x :: c.

我们进一步看到,有一个带有 f :: b->的函数应用程序.c 函数和 f x :: c 参数.由于 f 的参数类型为 b ,并且 f x 的类型为 c .因此,我们得出的结论是, b c 必须是相同的类型.

We furthermore see, that there is a function application with f :: b -> c the function, and f x :: c the parameter. Since the type of the parameter of f is b, and f x has as type c. We thus come to the conclusion, that b and c must be the same type.

因此,这意味着我们派生为类型:

This thus means that we derived as types:

x :: b
f :: b -> b

我们还可以通过确定 f(f x)的类型来分析 tw f x 的类型.由于 f x 的类型为 f x :: b ,而 f 的类型为 f :: b->b ,我们知道 f(f x)的类型是 f(f x):: b .因此,这意味着 tw 的类型为:

We can furthermore analyze the type of tw f x by determining the type of f (f x). Since f x has type f x :: b, and f has type f :: b -> b, we know that f (f x) has type f (f x) :: b. So that means that the type for tw is:

tw :: (b -> b) -> b -> b

如果我们用 b 代替 t ,那么我们将获得预期的类型签名.但是,由于 b t 只是变量,所以无关紧要.

If we substitute b for t, then we obtain the expected type signature. But since b and t are just variables, that does not matter much.

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

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