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
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:
2
[2]
(the first 2
from the sequence)[ [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:
Hopefully, this gives you enough information to figure out how to do this, without actually revealing the full source code!