2016-10-21 51 views
0

我必須做一個函數isFunction,它利用夫妻列表作爲參數,如果沒有重複考慮每對夫婦的第一個元素假的,如果有一個重複返回true。我可以在Ocaml的另一個「rec」函數中定義「rec」函數嗎?

例如:isFunction [(1,3);(2,40);(3,40)]返回trueisFunction [(1,3);(2,40);(1,40)]返回false,因爲重複1。

現在,我的代碼是:

let rec exist e = function 
    |[] -> false 
    |(a,_)::l -> e=a || exist e l;; 
let rec isFunction = function 
    |[]->true 
    |(a,_)::l -> not(exist a l) && isFunction l;; 

這完美的作品!但問題是:是否有另一種方法來定義isFunction而不定義其他輔助功能?

回答

1

你可以聲明exist作爲本地isFunction

let rec isFunction l = 
    let rec exist e = function 
    |[] -> false 
    |(a,_)::l -> e=a || exist e l 
    in 
    match l with 
    |[]->true 
    |(a,_)::l -> not(exist a l) && isFunction l 
+0

非常感謝您!這是完美的。 – Elirovi

1

您可以使用List.exists:

let isFunction = function 
    | []  -> true 
    | (a,_)::tl -> not (List.exists (fun (a',_) -> a'=a) tl) && isFunction l;; 
相關問題