是否可以用map,filter和reduce替换所有循环和if语句?

时间:2015-02-21 10:08:04

标签: functional-programming

有人告诉我你大部分时间都可以做到这一点,我想知道是否有某种证据表明你可以做到这一点。 (假设我们使用像Python这样的语言,它具有map,filter和reduce函数。)

1 个答案:

答案 0 :(得分:1)

鉴于您可以将任何功能传递给mapfilterreduce,是的。你可以用它做任何事情(虽然有些可能需要一些黑客攻击)。

例如,一个稍微难以模仿的例子,因为你需要保存状态(可以使用reduce,但不能在1语句中完成):

min_ = max_ = sum_ = items[0]
i = 0.
for item in items:
    i += 1
    min_ = min(item, min_)
    max_ = max(item, max_)
    sum_ += item
avg = sum_ / i

功能变体:

min_ = reduce(lambda x, y: min(x, y), items, items[0])
max_ = reduce(lambda x, y: max(x, y), items, items[0])
sum_ = reduce(lambda x, y: x + y, items, items[0])
avg = sum_ / len(items)

实际上......只是想到了在1减少声明中的方法:

min_, max_, sum_ = reduce(lambda x, y: (min(x[0], y), max(x[1], y), x[2] + y), items, [items[0]] * 3)
avg = float(sum_) / len(items)