如何解决删除警告此表达式在 Ocaml TL;DR:您获得的错误是典型的类型错误大部分更多详情修复/解决方法
为什么我会收到警告,此表达式应具有带有此代码的类型单元?虽然它做了它应该做的。
let matchInf42 list =
let a = ref 0 in
let lstLength = List.length list in
let rec matchInf4242 list =
match list with
|[]->[]
|m::body->
begin
if (m < 42) then a := !a + 1;
matchInf4242 body
end
in matchInf4242 list;
if(!a = lstLength) then -1 else 0
警告:
ocamlopt match.ml -o m
File "match.ml",line 14,characters 7-24:
14 | in matchInf4242 list;
^^^^^^^^^^^^^^^^^
Warning 10: this expression should have type unit.
解决方法
TL;DR:您获得的错误是典型的类型错误(大部分)
“主要”是因为,无可否认,这里不是“错误”而仅仅是“警告”,但似乎这种警告(Warning 10: non-unit-statement)总是值得解决(即避免)。
它实际上是以下模式的一个实例:
42; print_string "…" ;;
(* or more generally *)
any_value_not_having_type_unit; any_value_having_type_unit ;;
(* which would raise *)
> Characters 0-2:
> 42; print_string "…";;
> ^^
> Warning 10: this expression should have type unit.
> …- : unit = ()
更多详情
回想一下,unit
是一个单例类型(它只有 ()
的值)并且通常被选择来为“不返回特定值”但产生某些方面的函数分配一个返回类型-效果。
实际上,序列运算符正如我们所期望的那样“更通用/更灵活”:
# let semicolon i j = i; j ;;
val semicolon : 'a -> 'b -> 'b = <fun>
也就是说,它是not semicolon : unit -> 'b -> 'b
,因此当i; j
没有类型{{ 1}},只是一个警告,而不是类型错误。
修复/解决方法
避免此警告的两种策略:
-
要么依赖
i
函数忽略它unit
-
或者更改/修复计算序列左侧的方式(因此其类型为
ignore
)。在您的问题示例的特定情况下,写下这个就足够了(唯一的变化用符号
# ignore;; - : 'a -> unit = <fun> # ignore 42; print_string "…";; …- : unit = ()
表示):unit
补充说明
最后为了完整性(即使它不是您问题的明确一部分),请注意您考虑的示例函数也可以以更“功能性”的风格实现(没有引用或序列,也避免了调用§
函数预先):
let matchInf42 list =
let a = ref 0 in
let lstLength = List.length list in
let rec matchInf4242 list =
match list with
|[] -> () (*←§*)
|m::body->
begin
if (m < 42) then a := !a + 1;
matchInf4242 body
end
in matchInf4242 list;
if(!a = lstLength) then -1 else 0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。