问题
I want to take an Int value and a list that returns a list of lists where the Int value is what separates the values into groups. Here is an example below:
partitionBy :: Eq a => a -> [a] -> [[a]]
partitionBy = undefined -- pending implementation
Example:
partitionBy 0 [1,2,3,0,4,0,2,9,1] == [[1,2,3],[4],[2,9,1]]
回答1:
Assuming every separator (sep
) value encountered at the start or end, as well as in succession would create an empty list, here's what I came up with:
partitionBy :: Eq a => a -> [a] -> [[a]]
partitionBy sep l = partitionByAux l []
where
partitionByAux (h : t) acc | sep == h = acc : partitionByAux t []
partitionByAux (h : t) acc = partitionByAux t (acc `snoc` h)
partitionByAux [] acc = [acc]
> partitionBy 0 [1,2,3,0,4,0,2,9,1]
[[1,2,3],[4],[2,9,1]]
> partitionBy 0 [0,1,2,3,0,4,0,2,9,1,0]
[[],[1,2,3],[4],[2,9,1],[]]
> partitionBy 0 [1,2,3,0,4,0,0,0,2,9,1]
[[1,2,3],[4],[],[],[2,9,1]]
Edit:
the function snoc
is imported from the module Data.List.Extra
, and what it does is append an element to the end of a list. Alternatively, you can write the said function like this:
snoc :: [a] -> a -> [a]
snoc [] a = [a]
snoc (h : t) a = h : t `snoc` a
Update:
Applied suggested modifications by @WillNess to partitionByAux
for faster execution:
partitionByAux (h : t) acc | sep == h = reverse acc : partitionByAux t []
partitionByAux (h : t) acc = partitionByAux t (h : acc)
partitionByAux [] acc = [reverse acc]
来源:https://stackoverflow.com/questions/65281573/how-do-we-partition-list-in-haskell-by-a-separator-element-of-the-list