OCaml中抽象数据类型的匹配元素

问题描述 投票:0回答:1

我是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 b-tree custom-data-type
1个回答
0
投票

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 

这很短,更易于理解,并且不易出错。

© www.soinside.com 2019 - 2024. All rights reserved.