Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Functional programming 功能文体中的多集理解_Functional Programming - Fatal编程技术网

Functional programming 功能文体中的多集理解

Functional programming 功能文体中的多集理解,functional-programming,Functional Programming,是否有人知道(在任何语言中)一个函数/习惯用法,它接受一个集合并返回由一个或多个谓词确定的两个或多个子集 以命令式的方式很容易做到这一点,例如: a = b = [] for x in range(10): if even(x): a.append(x) else: b.append(x) 或者稍微好一点: [even(x) and a.append(x) or b.append(x) for x in range(10)] 由于集合理解返回

是否有人知道(在任何语言中)一个函数/习惯用法,它接受一个集合并返回由一个或多个谓词确定的两个或多个子集

以命令式的方式很容易做到这一点,例如:

a = b = []

for x in range(10):
    if even(x):
        a.append(x)
    else:
        b.append(x)
或者稍微好一点:

[even(x) and a.append(x) or b.append(x) for x in range(10)]
由于集合理解返回基于单个谓词的单个列表(实际上它只是一个映射),因此我认为应该有某种东西基于二进制谓词或多个谓词将输入拆分为两个或多个容器

我能想到的最简洁的语法是:

>> def partition(iterable, *functions):
>>    return [filter(f,iterable) for f in functions]
>> partition(range(10), lambda x: bool(x%2), lambda x: x == 2)
[[1, 3, 5, 7, 9], [2]]

Ruby的
Enumerable
mixin有一个方法可以实现您所描述的功能。

搜索收益率

partition
函数将谓词作为一个列表,并分别返回满足谓词和不满足谓词的元素列表对;i、 e

partition p xs == (filter p xs, filter (not . p) xs)
如果您查看其源代码并将其转换为Python

def partition(predicate, sequence):
    def select((yes, no), value):
        if predicate(value):
            return (yes + [value], no)
        else:
            return (yes, no + [value])
    return reduce(select, sequence, ([], []))

这是非常好的功能。与最初的版本不同,它并不懒惰,但在Python中实现这一点有点困难。

这与我想要的非常接近。我认为一个更好的方法可能是允许多个函数传入。啊哈,我忘了Hoogle允许基于类型签名的搜索!我的好奇心已经满足了,谢谢。