Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning 10: this expression should have type unit

Tags:

ocaml

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]

like image 571
user1008820 Avatar asked Oct 31 '11 04:10

user1008820


1 Answers

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.

like image 192
nlucaroni Avatar answered Oct 01 '22 21:10

nlucaroni