How do I determine type of Haskell functions? [duplicate]

扶醉桌前 提交于 2021-02-19 01:18:05

问题


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

functions:

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

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

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

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

Supposed type of tw:

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

thanks!


回答1:


Let us analyze the function tw:

tw f x = f (f x)

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.

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.

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

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

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.



来源:https://stackoverflow.com/questions/58285479/how-do-i-determine-type-of-haskell-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!