ocaml type missmatch unit vs list

喜欢而已 提交于 2019-12-02 17:28:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!