Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Removing duplicates from list with function

Tags:

list

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

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]

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

like image 790
Bobson Avatar asked Feb 18 '26 14:02

Bobson


2 Answers

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 []
like image 124
John Palmer Avatar answered Feb 21 '26 13:02

John Palmer


Just for completeness: in F# 4.0 the List module now has the distinct function doing exactly what OP wants.

List.distinct [1; 2; 2; 3; 3; 3];;
val it : int list = [1; 2; 3;]
like image 44
Good Night Nerd Pride Avatar answered Feb 21 '26 14:02

Good Night Nerd Pride