2017-02-10 99 views
1

我想比較例如: 我有一個列表l: [11,2,2,3]x = 11, y = 2, z = 2 and t = 3。 我想比較x to y, z, t,然後比較y to z, t,然後z to t. 如果它們是等於,那麼將它們放入列表中,否則繼續比較列表的其餘部分。 這是我迄今爲止所做的,但它並沒有給我正確的答案。我期待的結果是列表:[y, z] => [2,2]你能幫我嗎?謝謝。遞歸比較遞歸列表中的元素

let rec compare_element_list l = 
    match l with 
    | [] | [_] -> [] 
    | x :: y :: [] -> 
     if x = y 
     then 
     (*add x and y into a list*) 
     let result = x :: y :: [] in 
     result 
     else 
     [] 
    | x :: y :: tl -> 
     if x = y 
     then 
     let result = x :: y :: [] in 
     result; compare_element_list tl 
     else 
     match tl with 
     | [] -> [] 
     | [z] -> 
      if x = z then 
      let result = x :: z :: [] in result 
      else [] 
     | z :: tl' -> 
      if x = z 
      then 
      let result = x :: z :: [] in 
      result; compare_element_list tl' 
      else compare_element_list tl' 
+0

很難幫助沒有更仔細的問題陳述,對不起。 –

回答

2

對於列表中的每個元素,只需檢查它是否是列表中其餘部分的成員。您可以獲得以下功能:

let rec compare_element_list = function 
    | [] | [_] -> [] 
    | x::tail -> 
    let result = compare_element_list tail in 
    if List.mem x tail 
    then x::x::result 
    else result 

但是,上面的這個函數不是尾遞歸的。這裏是尾遞歸版本:

let rec compare_element_list buf = function 
    | [] | [_] -> buf 
    | x::tail -> 
    if List.mem x tail 
    then compare_element_list (x::x::buf) tail 
    else compare_element_list buf tail 

(申請尾REC版本,你需要提供一個空的緩衝區: compare_element_list [] [11;2;2;3]