I am new to OCaml and functional programming, so I’ve got a question about functions and types.
Let’s say I have a function: let f x y z = x ( y ^ z );;.
I’d like to find its type without using the compiler.
When I consider the right side: x ( y ^ z ). It seems that both y and z are type of string, as they are concatenated using the ^ operator. Then x must be a function which takes ( y ^ z ) (string) as an argument and returns an unknown type 'a.
That means that x is: val x: (string -> 'a).
I follow the idea that functions can have only one argument in functional programming.
Next, I consider the left side (this is where I don’t fully understand it) let f x y z. x is a function which takes y as an argument and then there’s z.
Does it mean that y is also a function which takes z and then returns a string or y is only a string?
For sure the return type of y will be a string, the same goes for z since they appear on the right side as (y ^ z). But is it possible that both y and z are the functions?
Overall the left side seems to be: fun x -> fun y -> fun z which is (string -> ‘a) -> string -> string and the whole function f returns an unknown type 'a which also matches with the return type of the right side.
The signature will be (string -> ‘a) -> string -> string -> ‘a.
Is it correct or do I misunderstand some parts? I will appreciate any help .
Hi,
The only thing that seems to have you slightly confused is the OCaml syntax for functions definitions. let f x y z = ... is treated as let f = fun x -> fun y -> fun z -> ...
So that in the end you are right ! It’s easy to check the type inferred by the compiler for f in the toplevel (utop).
You can also see the manual for more details on the syntax:
Hey,
thanks for the quick reply! So to make it clear, y and z on the left side - fun y -> fun z are the functions that each of them returns a string and then the strings are concatenated like here ( y ^ z ),
or y and z are strings, but are passed as parameters of functions?
A function which has 2 arguments can be seen as a function with 1 argument which itself returns a function with 1 argument (and repeat for more than 2 arguments). What you say after is wrong so I suspect there’s a misunderstanding.
For instance f has 3 arguments.
x is a function which takes y as an argument and then there’s z.
Does it mean that y is also a function which takes z and then returns a string or y is only a string?
x is a function of type string -> 'a, with no special relation to y. y and z are strings.
Overall the left side seems to be: fun x -> fun y -> fun z which is (string -> ‘a) -> string -> string
No.
First, fun without a -> ... (where ... is some expression) makes no sense.
Second, the type (string -> ‘a) -> string -> string has nothing to do with f’s type (string -> ‘a) -> string -> string -> 'a (it may look like they’re related, but that’s because by convention we omit the parentheses so f’s type is