首页 > 解决方案 > 删除列表中两次出现之间的元素

问题描述

我必须创建一个函数来获取列表并返回列表,但没有出现之间的元素。

例如: [ 1 ; 2 ; 3;4;2 ; 7 ; 14; 21; 7 ; 5 ] -> [1; 2;7; 5]

我想,为了做到这一点,我将占据列表的头部,然后看看尾部是否还有另一个出现,所以我浏览了列表,当我找到这个出现时,我删除了它们之间的所有内容,我只保留一个他们。

首先我尝试了这样的事情:

let rec remove list = match list with 
    | [] -> []
    | h::t -> if(List.mem h t) then
                (*Here I would like to go through the list element by element to
                 find the occurence and then delete everything between*)
               else
                 remove t 

所以对于我没有成功的部分,我做了一个函数,允许在两个给定点之间分割一个列表,就像这样:

let slice list i k =
   let rec take n = function
     | [] -> []
     | h :: t -> if n = 0 then [] else h :: take (n-1) t
   in
   let rec drop n = function
     | [] -> []
     | h :: t as l -> if n = 0 then l else drop (n-1) t
   in
   take (k - i + 1) (drop i list);;

(*Use: slice ["a";"b";"c";"d";"e";"f";"g";"h";"i";"j"] 2 3;;*)

我还有这个函数可以让我获取列表中点的索引:

let index_of e l = 
  let rec index_rec i = function
    | [] -> raise Not_found
    | hd::tl -> if hd = e then i else index_rec (i+1) tl
  in
  index_rec 0 l ;;
(*Use: index_of 5 [1;2;3;4;5;6] -> return 4*)

但我真的不知道如何将它们结合起来以获得我的期望。

标签: listocaml

解决方案


这是我所做的:

let rec remove liste = 
    let rec aux l el = match l with 
    | [] -> raise Not_found
    | x :: xs -> if el = x then try aux xs el with Not_found -> xs 
        else aux xs el in 
    match liste with 
    | [] -> []
    | x :: xs -> try let r = x :: aux xs x in remove r with Not_found -> x :: remove xs;;

我的 aux 函数返回在 l 中最后一次出现 el 之后的列表。如果您有任何问题或需要更多解释,请在评论中问我


推荐阅读