我们如何通过列表的分隔符在Haskell中对列表进行分区? [英] How do we partition list in Haskell by a separator element of the list?

查看:37
本文介绍了我们如何通过列表的分隔符在Haskell中对列表进行分区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个Int值和一个列表,该列表返回一个列表列表,其中Int值将这些值分成几组.下面是一个示例:

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

示例:

partitionBy 0 [1,2,3,0,4,0,2,9,1] == [[1,2,3],[4],[2,9,1]]

推荐答案

假设在开始或结束时以及相继遇到的每个分隔符( sep )值都将创建一个空列表,这是我想出了什么:

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]]

函数 snoc 是从模块 Data.List.Extra 导入的,其作用是将元素添加到列表的末尾.另外,您可以这样编写所述函数:

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

更新:

@WillNess建议对 partitionByAux 进行修改,以提高执行速度:

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]

这篇关于我们如何通过列表的分隔符在Haskell中对列表进行分区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆