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!
If you are using an interactive Haskell prompt (like GHCi) you can type :t <expression> and that will give you the type of an expression. e.g.
if it is just about knowing if the list contains duplicates you can use the nub function in Data. List like so: hasDup l = nub l == l (nub removes all duplicates... so this will be true only if there are no duplicates in the list.)
Everything in Haskell has a type, so the compiler can reason quite a lot about your program before compiling it. Unlike Java or Pascal, Haskell has type inference.
Haskell is a functional language and it is strictly typed, which means the data type used in the entire application will be known to the compiler at compile time.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With