Bartek
Bartek

Reputation: 33

Function type signatures

I tried to find this somewhere in internet, but I failed to do this. I want to learn OCaml and that's difficult to understand for me, how to do this.

My question is - how can I easy write a function, when I have a signature. For example - I have a signature like this:

((int -> int) -> int -> int -> int) -> (int -> int) -> int -> int -> int

and I want to write a function, that have signature like this above. Would someone help me or try to explain this? I would be very grateful :)

Upvotes: 0

Views: 7061

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

A function with type 'a -> 'b, takes values of some type 'a and returns values of some type 'b. To use specific types, a function of type int -> int takes an int and returns an int. This is the type of integer negation, for example.

One way to look at a function with type 'a -> 'b -> 'c is that it takes two values, of type 'a and 'b, and returns a value of type 'c. A specific example would be the type int -> int -> int, which is the type of integer addition (say):

# (+);;
- : int -> int -> int = <fun>

This pattern continues for more arguments.

The type you give has this type at the high level: 'a -> 'b -> 'c -> 'd -> 'e. So, it's a function with four arguments.

The first argument has type (int -> int) -> int -> int -> int, which is itself quite complicated. The second argument has type int -> int, described above. The third and fourth arguments have type int. The function returns an int.

Using this same analysis on the first argument, you can see that it's a function with three arguments. The first is a function of type int -> int, and the second and third are of type int. This function returns an int.

Here's a function of type (int -> int) -> int -> int -> int:

let myfun f a b =
    (f a) + a + b

You can see the type in the OCaml toplevel:

# let myfun f a b =
     (f a) + a + b;;
val myfun : (int -> int) -> int -> int -> int = <fun>
# 

You should be able to work out the rest. I don't want to take all the enjoyment out of the problem by giving a full answer.

Upvotes: 5

Related Questions