Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 905
lsval Avatar asked Oct 08 '19 11:10

lsval


People also ask

How do you check types in Haskell?

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.

How do you check for duplicates in a list Haskell?

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.)

Does every Haskell function have a type?

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.

What is Haskell function type?

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.


1 Answers

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.

like image 181
Willem Van Onsem Avatar answered Oct 13 '22 04:10

Willem Van Onsem