F#使用功能从列表中删除重复项 [英] F# Removing duplicates from list with function

查看:70
本文介绍了F#使用功能从列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个接受列表并返回包含重复项的列表的函数.

I want to create a function that takes a list and returns a list with removed duplicates.

let removedupes list1 =
  let list2 = []
  let rec removeduprec list1 list2 =
    match list1 with
    | [] -> list2
    | head :: tail when mem list2 head = false -> head :: removeduprec tail list2
    | _ -> removeduprec list1.Tail list2
  removeduprec list1 list2

我正在使用此"mem"功能浏览列表,并查看该值是否已经存在,在这种情况下,我想继续进行递归操作.

Im using this "mem" function to go trough the list and see if the value already exists and in that case i want to continue with the recursion.

let rec mem list x = 
  match list with
  | [] -> false
  | head :: tail -> 
    if x = head then true else mem tail x 

当我测试此代码时,我得到

When i test this code i get

let list1 =  [ 1; 2; 3; 4; 5; 2; 2; 2]
removedups list1;;
val it : int list = [1; 2; 3; 4; 5; 2; 2; 2]

我以为是"head :: removeuprec tail list2",但对于f#来说还很陌生,所以不能完全确定它是如何工作的.

Im thinking that the "head :: removeduprec tail list2", but im quite new to f# so not completely sure how this works.

推荐答案

我重写了一些使事情变得更简单的逻辑.问题在于,您需要在创建时将它们添加到 list2 中,而不是在以后添加-我将 :: 移到了调用内部,就像这样

I rewrote some of the logic to make things simpler. The problem was that you needed to add things to list2 as it was created, rather than afterwards - I moved the :: to inside the call like so

let rec mem list x =
  match list with
  | [] -> false
  | head :: tail ->
    if x = head then true else mem tail x

let removedupes list1 =
  let rec removeduprec list1 list2 =
    match list1 with
    | [] -> list2
    | head :: tail when mem list2 head = false -> removeduprec tail (head::list2)
    | h::t -> removeduprec t list2
  removeduprec list1 []

这篇关于F#使用功能从列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆