【问题标题】:Can all loops and if statements be replaced by map, filter, and reduce?所有循环和 if 语句都可以用 map、filter 和 reduce 代替吗?
【发布时间】:2015-02-21 20:44:34
【问题描述】:

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

【问题讨论】:

  • 可以传递哪些函数?我可以通过映射一个虚拟的元素列表并使用 ifs 和循环传递任意代码来欺骗您的问题陈述。

标签: functional-programming


【解决方案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 个 reduce 语句中做到这一点:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    相关资源
    最近更新 更多