Tosh
Tosh

Reputation: 130

ocaml type missmatch unit vs list

For this signature

val chooser: string list * string list -> string list

and this implementation

 let rec chooser (inputList, trueList) = match inputList with
      [] -> []
    | iH::iT -> if (List.hd trueList)="True" 
        then iH::(chooser iT List.tl trueList)

I am getting the following error:

Error: This variant expression is expected to have type unit The constructor :: does not belong to unit

What am I doing wrong?

Upvotes: 0

Views: 105

Answers (2)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

The result of if ... then with no else has to be unit, because the value will be () (the value of type unit) when the expression is false.

In other words, you need an else part for your if to get the type you want. What should the value be when the comparison is false?

Upvotes: 1

Pierre G.
Pierre G.

Reputation: 4441

the else part is not explicitly defined - so when the condition is not statisfied, the else part is () (that is the unit). The compiler typechecks iH::(chooser iT List.tl trueList) as unit which is cannot be the case:

 if cond
    then A
    else B

A and B have the same types.

Upvotes: 1

Related Questions