BostonMan
BostonMan

Reputation: 161

OCaml Type and Type Inference

I am having a bit of trouble determining OCaml Types. Why is the type for the following expression for:

let f x y z = z (y::x)

'a list->'a->('a list->'b)->'b

And what does the z (y::x) mean? I know y::x means to append an element y to list x, but what does the z do?

Thanks!

Upvotes: 1

Views: 126

Answers (1)

Steve Vinoski
Steve Vinoski

Reputation: 20004

First, note that y::x prepends, not appends, an element y to list x.

The four parts of the type of f can be explained as follows:

  • The first argument to function f is x, so the first part of the type of f is 'a list, which is consistent with the use of x as a list in the definition of f.
  • The second part of the type of f is 'a, which is consistent with prepending element y to the list x, since if x is an 'a list, y must be an 'a.
  • The third argument of f is z, which must be a function taking an 'a list as its first argument given how it's used in the definition of f. Therefore the third part of the type of f is ('a list -> 'b), where 'b is the return type of z.
  • Finally, the return type of f is the same as the return type of z, so the final part of the type of f is 'b'.

Upvotes: 3

Related Questions