How to combine equal sequence elements (functional programming)?

后端 未结 4 1935
情书的邮戳
情书的邮戳 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 15:59

    I guess that the reduce function you are referring to is the same as the fold function in F#:

    val fold : ('State -> 'Value -> 'State) -> 'State -> 'Value list -> 'State
    

    This takes a list of values, together with an initial state and a function that transforms the state while iterating through the values of the list.

    You can do what you want in a single fold. There are a couple of things that you'll need to keep in the state. Imagine you are somewhere in the middle of 1,1,2,2,3 (say, on the second 2). Now you'll need:

    • The value that you are currently collecting - that is 2
    • A list of values containing the currently collected values - that is [2] (the first 2 from the sequence)
    • A list of lists of values you collected previously - that is [ [1; 1] ].

    You would start with an initial state -1, [], [] (using -1 as some value that won't appear in your input). Then you need to write the function that transforms the state based on a current value. This needs to handle a couple of situations:

    • When the value is not the same as the values you've been collecting, you need to add the list of collected values to the list of lists (unless it is empty)
    • When the value is the same, you need to add it to the list of values collected now and continue

    Hopefully, this gives you enough information to figure out how to do this, without actually revealing the full source code!

提交回复
热议问题