简体   繁体   中英

What is the type of this function definition "twice f x = f (f x)"

This is an excerice question from a book I'm reading now, so what is the type of this definition:

twice f x = f (f x)

I understand how the function should work, but I could not figure out the right syntax for it,
It takes two arguments, the first is a function and the second is a basic type I think and apply the function twice, one for x and one for the return of (fx) , this is what is was trying to do but obviously it's a wrong syntax

twice :: (f -> a) -> a

Can you help me find the type?

You should deducting type of twice starting with it's parameters.

Start with x , it has type x :: _ , but we have no idea what it is, lets call it's type a : x :: a .

Then we have f , it's a function, from fx we can tell it accepts one argument of type a : f :: a -> _ , let's call new unknown type b : f :: a -> b .

So fx should be of type b : (fx) :: b right?

But from f (fx) we can tell that (fx) should be a , so we can guess that a and b are actually the same type, so we can drop b and tell that f :: a -> a .

And now we can tell what type twice is: it's a function that takes a -> a function and value of type a and returns result of the first argument function (so a again).

So we have twice :: (a -> a) -> a -> a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM