问题
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