问题
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?
回答1:
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?
回答2:
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.
来源:https://stackoverflow.com/questions/50191899/ocaml-type-missmatch-unit-vs-list