Ocaml utop中的模式匹配更严格?
例如,有一个函数测试列表是否单调递增,源代码和测试用例是:Ocaml utop中的模式匹配更严格?,ocaml,utop,Ocaml,Utop,例如,有一个函数测试列表是否单调递增,源代码和测试用例是: open Printf let rec mon_inc (numbers : int list) : bool = match numbers with | [] -> true | _ :: [] -> true | hdn :: tln -> (hdn <= (List.hd tln)) && mon_inc(tln) let a = [1;2;5;5;8]
open Printf
let rec mon_inc (numbers : int list) : bool =
match numbers with
| [] -> true
| _ :: [] -> true
| hdn :: tln -> (hdn <= (List.hd tln)) && mon_inc(tln)
let a = [1;2;5;5;8]
let b = [1;2;5;4;8]
let c = [8]
let d = []
let e = [7;8]
let () =
printf "The answer of [1;2;5;5;8]: %B\n" (mon_inc a)
let () =
printf "The answer of [1;2;5;4;8]: %B\n" (mon_inc b)
let () =
printf "The answer of [8]: %B\n" (mon_inc c)
let () =
printf "The answer of []: %B\n" (mon_inc d)
let () =
printf "The answer of [7;8]: %B\n" (mon_inc e)
但是,当我想在utop中使用此功能时,它显示:
utop # #use "inc.ml";;
File "inc.ml", line 7, characters 29-40:
Error: This expression has type int option
but an expression was expected of type int
这是因为您已经在顶级中打开了Core.Std模块 Std是OCaml标准库上的一个覆盖层,具有不同的接口。例如,在标准库函数中,List.hd返回类型为“a”的值,如果List为空,则引发异常。在Janestreet的版本函数List.hd中有一个不同的类型-它返回一个选项,如果列表为空,它的计算结果为None,如果列表为空,它的计算结果为某个值。考虑添加
open Core.Std
这是因为您已在顶级中打开了Core.Std模块 Std是OCaml标准库上的一个覆盖层,具有不同的接口。例如,在标准库函数中,List.hd返回类型为“a”的值,如果List为空,则引发异常。在Janestreet的版本函数List.hd中有一个不同的类型-它返回一个选项,如果列表为空,它的计算结果为None,如果列表为空,它的计算结果为某个值。考虑添加
open Core.Std
对于inc.ml.的顶部,这可能是由于您的顶层打开了
Core
,它提供了一个返回选项的List.hd
。在这种情况下,您可以通过更改匹配方式来解决问题,以完全删除列表.hd
:
let rec mon_inc = function
| []
| _::[] -> true
| x::y::rest -> x <= y && mon_inc rest
让rec mon_inc=函数
| []
|_u::[]->正确
|x::y::rest->x这可能是由于顶级打开了Core
,它提供了一个返回选项的List.hd
。在这种情况下,您可以通过更改匹配方式来解决问题,以完全删除列表.hd
:
let rec mon_inc = function
| []
| _::[] -> true
| x::y::rest -> x <= y && mon_inc rest
让rec mon_inc=函数
| []
|_u::[]->正确
|x::y::rest->x