I'm trying to create a list of functions in Ocaml but I keep getting a warning. Any idea why?
let f = [fun x -> -x;fun x -> x+2;fun x -> x*x]
The semi-colon is also used to end functions that are used for their side-effects. The warning comes about when the return type of these functions is not unit
(in this case int
); they are just warnings since you may have intended to only use the side-effects, normally it is an error. This is an aside, but to suppress these warnings programmatically and safely use the ignore
function, as in ignore (x+2);
.
Back to your problem, in it (and expanding the semi-colons to their equivalence; and modifying the variables for each function) you are actually writing,
(fun x ->
let _ = -x in
(fun y ->
let _ = y+2 in
(fun z -> z*z)))
Or, another example as gasche points out,
(fun x ->
-x;
(fun y ->
y+2;
(fun z -> z*z)))
You can tell from the type returned, (int -> int -> int -> int) list
that something is instantly amiss from your intentions. You'll need to add parenthesis around each, like (fun x -> x+2);
to actually create a list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With