How do we partition list in Haskell by a separator element of the list?

耗尽温柔 提交于 2021-02-05 12:22:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!