2014-09-29 72 views
0

例如,有一個測試,如果列表單調遞增函數,源代碼和測試案例是:烏托邦模式匹配更嚴格?

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) 

編譯並運行代碼:

$ corebuild inc.native 
$ ./inc.native 
The answer of [1;2;5;5;8]: true 
The answer of [1;2;5;4;8]: false 
The answer of [8]: true 
The answer of []: true 
The answer of [7;8]: true 

然而,當我想在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 

回答

3

這可能是由於您的頂層開放Core,它提供了返回選項的List.hd。在這種特殊情況下,您可以通過更改您的匹配方式來完全刪除List.hd

let rec mon_inc = function 
    | [] 
    | _::[] -> true 
    | x::y::rest -> x <= y && mon_inc rest 
3

這是因爲你已經在頂層開Core.Std模塊。

Core.Std是一個覆蓋OCaml的標準庫,具有不同的接口。例如,在標準庫函數中,List.hd返回類型'a'的值,如果列表爲空,則會引發異常。在Janestreet的版本函數中,List.hd具有不同的類型 - 它返回'一個選項,如果列表爲空,則返回None,如果不是,則返回Some值。考慮添加

open Core.Std 

到inc.ml的頂部。