How can I remove duplicates in an F# sequence without using references

前端 未结 6 388
南方客
南方客 2021-01-20 09:07

I have a sorted sequence and want to go through it and return the unique entries in the sequence. I can do it using the following function, but it uses reference variables a

6条回答
  •  被撕碎了的回忆
    2021-01-20 09:54

    The solution below, preserves order of elements and returns only the first occurance of an element in a generic list. Of course this generates a new List with the redundant items removed.

    //  ****  Returns a list having subsequent redundant elements removed
    let removeDuplicates(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
        lst 
        |> List.rev
        |> fun x -> List.foldBack f x []
        |> List.rev
    //  **** END OF FUNCTION removeDuplicates
    
    val removeDuplicates : 'a list -> 'a list when 'a : equality
    val testList : int list = [1; 4; 3; 1; 2; 2; 1; 1; 3; 4; 3]
    val tryAbove : int list = [1; 4; 3; 2]
    

提交回复
热议问题