1

One of the exercises I am trying has defined a function as follows:

twice f x = f (f x)

When I print the type of twice I see:

Main> :t twice
twice :: (a -> a) -> a -> a

Not sure I understand the output here. So twice takes an input of type function (which is of type a -> a). Is this correct? If so then how was the f evaluated to be of type function (a -> a)? And then what is the return type of twice here?

2 Answers 2

4
twice    f            x  =   f (f x)
twice :: (a -> a) ->  a  ->  a

it is like this.

f is of type a -> a, x is of type a, f (f x) is of type a.

You should pass f as a -> a function, such as * 2

Sign up to request clarification or add additional context in comments.

2 Comments

Ah I see it now. So how was the type of 'f' evaluated to be of type a->a. How did the interpreter deduce it's type? I have not defined 'f' anywhere.
Someone seem to have asked a similar question here: stackoverflow.com/questions/42243902/…
1

Yes, it's correct.

f has a type of a -> a

It takes x which has a type of a and should be able to use his output again, so the output should be the same type as the input.

And twice has the same output type as a call from f, so a.

Which gives us this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.