user1008820
user1008820

Reputation: 181

Warning 10: this expression should have type unit

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]

Upvotes: 7

Views: 12437

Answers (1)

nlucaroni
nlucaroni

Reputation: 47934

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.

Upvotes: 10

Related Questions