3 people like it.

Remove duplicate list elements

I have been working on my "Functional Style" and like to think that I have improved a bit. The list order is no longer maintained in this snippet; however as the order change is simply a feature of the foldBack process the reversal of input and reversal of output is a reliable (and efficient?) fix.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
let removeDuplicatesB(lst : 'a list) = 
    let f item acc =
        match acc with 
        | [] -> [item]
        | _ ->
            match List.exists(fun x -> x = item) acc with
            | false -> item :: acc
            | true -> acc
    List.foldBack f lst []
//  TEST BELOW NOTE: the list order is not maintained by the above snippit
//  As the order change is simply a feature of the foldBack process
//  the reversal of input and reversal of output is a reliable fix.  
["e"; "j"; "f"; "h"; "d"; "i"; "k"; "l"; "g"; "a"; "b"; "c"; "d"; "e"; "f"; "g" ] 
|> List.rev 
|>removeDuplicatesB 
|> List.rev
val removeDuplicatesB : lst:'a list -> 'a list (requires equality)

Full name: Script.removeDuplicatesB
val lst : 'a list (requires equality)
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
val f : ('b -> 'b list -> 'b list) (requires equality)
val item : 'b (requires equality)
val acc : 'b list (requires equality)
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val exists : predicate:('T -> bool) -> list:'T list -> bool

Full name: Microsoft.FSharp.Collections.List.exists
val x : 'b (requires equality)
val foldBack : folder:('T -> 'State -> 'State) -> list:'T list -> state:'State -> 'State

Full name: Microsoft.FSharp.Collections.List.foldBack
val rev : list:'T list -> 'T list

Full name: Microsoft.FSharp.Collections.List.rev

More information

Link:http://fssnip.net/b3
Posted:5 years ago
Author:visProcessEngg
Tags: remove duplicates , list , tail recursion