How to combine equal sequence elements (functional programming)?

后端 未结 4 1939
情书的邮戳
情书的邮戳 2021-01-20 15:42

I want to write a function that takes in a sequence <1,1,2,2,3> and returns the sequence with equal elements grouped like <<1,1>, <2,2>, <3>>.

I\'m u

4条回答
  •  不知归路
    2021-01-20 16:01

    If F# is your language, simply use the Seq.groupBy function:

    input |> Seq.groupBy id |> Seq.map snd
    

    Otherwise,

    I assume that your language supports Seq.distinct, Seq.fold, Seq.map, and Seq.init. The F# version of these functions can be found in this document.

    Then you can do the steps below:

    1) Make a distinct seq of the input seq with Seq.distinct:

    input |> Seq.distinct
    

    2) Write a function that counts the number of occurrences of a value in a seq by using Seq.fold:

    let count x theSeq =
        theSeq
        |> Seq.fold (fun n e -> if x = e then n+1 else n) 0
    

    3) Use the count function to decorate each element of the distinct seq with the number of its occurrences in the input seq:

    Seq.map (fun x -> (x, count x input))
    

    4) Finally, use Seq.init to replicate the equal elements:

    Seq.map (fun (x, count) -> Seq.init count (fun i -> x))
    

    The whole code:

    let count x theSeq =
        theSeq
        |> Seq.fold (fun n e -> if x = e then n+1 else n) 0
    
    input
    |> Seq.distinct
    |> Seq.map (fun x -> (x, count x input))
    |> Seq.map (fun (x, count) -> Seq.init count (fun i -> x))
    

提交回复
热议问题