函数式编程:过滤然后映射的术语



有时我发现自己想要过滤一个集合,然后映射结果。

例如,在 JavaScript 中:

var completedStepIds = steps.filter(function(step) {
    return step.isComplete;
}).map(function(step) {
    return step.id;
});

或者在 C#/LINQ 中:

var completedStepIds = 
    from step in steps
    where step.IsComplete
    select step.Id
;

在功能用语中,这种过滤器-然后映射组合有一个术语吗?

我想你想要列表理解:

[f(x) | x <- list, g(x)] # Haskell
[f(x) for x in iterable if g(x)] # Python

好吧,jQuery的map是这样工作的,这是一种伪装的列表理解:

> $.map([1,2,3], function(x) { return x != 2 ? 2 * x: null })
[2, 6]

另一方面,原型根本不过滤(这是正统的做法,地图不应该减少):

> [1,2,3].map(function(x) { return x != 2 ? 2 * x: null })
[2, null, 6]

我不知道您使用的是哪个库,但是您始终可以编写自己的抽象,从映射中清除null/undefined:

steps.map_and_filter(function(step) {
    return step.isComplete ? step.id : null;
})

最新更新