OCaml中如何比较字符串?使用比较运算符报错求助
解决OCaml字符串比较的错误问题
错误原因
OCaml中默认的<、<=等比较运算符仅支持整数类型直接比较,字符串无法直接使用这些运算符,这就是你遇到类型不匹配错误的原因。
修正方案
单个字符串比较的修正
将直接使用运算符的写法,改为调用String.compare函数并判断返回值:
- 原错误代码:
"a" < "b" - 修正后代码:
String.compare "a" "b" < 0
String.compare s1 s2的返回规则:
- 返回负数:s1小于s2
- 返回0:s1等于s2
- 返回正数:s1大于s2
递归排序检查函数的修正
修改is_ordered函数中字符串比较的部分,替换为String.compare的判断逻辑:
(* Given a list of strings, check to see if it is ordered, i.e. whether earlier elements are less than or equal to later elements. *) let rec is_ordered (ls: string list): bool = match ls with | head::[] -> true | head1::(tail1::tail2) -> ((String.compare head1 tail1 <= 0) && is_ordered(tail1::tail2)) | _ -> false
测试验证
在utop中测试修正后的代码:
- 测试有序列表:
is_ordered ["a"; "b"; "c"]→ 返回true - 测试无序列表:
is_ordered ["a"; "c"; "b"]→ 返回false
内容的提问来源于stack exchange,提问作者Murphy
相关产品推荐
相关产品推荐

