我是OCaml的初学者。现在,我正在练习一些代码。我刚刚测试了自定义数据类型(我认为这不是真正的“我的”自定义),但是遇到了错误,这是代码
type btree =
| Empty
| Node of (int * btree * btree)
let rec mem : int -> btree -> bool
= fun n t ->
match t with
|Empty -> false
|Node (a,b,c) -> if a = n then true
else if mem n b then true
else if mem n c then true;;
OCaml说最后一个'true;应该是类型单位,但我计划此mem函数应返回布尔值。我不明白为什么'true'不适合它...顺便说一下,函数mem旨在检查btree't'是否包含int'n'。
OCaml具有if
表达式的两种形式:
if <cond> then <exp1> else <exp2>
和
if <cond> then <exp1>
[在后一种形式中,else
分支被省略,并且默认为else ()
,其中()
是类型单位的值。换句话说,后一种形式是语法糖
if <cond> then <exp1> ::= if <cond> then <exp1> else ()
因此,例如,在编写时,
if friendly then "Say hello"
与]相同>
if friendly then "Say hello" else ()
此表达式的格式不正确,因为根据条件(
friendly
),它可能会返回string
类型的值或unit
类型的值。在OCaml中,每个表达式应该只有一种类型。
特别是转到您的代码,您有一个if/then/else
表达式链,最后一个else
表达式被省略了,可能是因为您认为它应该默认为false
(不是这种情况)。您的代码在语义上正确的版本是
if a = n then true else if mem n b then true else if mem n c then true else false
但是,此代码可以改进。在OCaml中,
(||)
和(&&)
运算符发生短路,即,如果x || y
为真,则在y
中不评估表达式x
。所以当我们有一个形式的表达式
if <cond> then true else <bool-expr>
我们总是可以重写它,它更简洁(更容易理解)
<cond> || <bool-expr>
因此,您的代码可以重写为
a = n || mem n b || mem n c
这很短,更易于理解,并且不易出错。