首页 > 解决方案 > 无法决定是否应该使用高阶函数

问题描述

简单的方法

def add(listt, addend):
    sums = list()
    for l in listt: sums.append(l + addend)
    return sums
print(
    add(
    [34,19], 6)
      )

WITH HIGHER-ORDER FUNCTION(来自教学函数式编程的一页)

def hof_add(increment):
# Create a function that loops and adds the increment
def add_increment(numbers):
    new_numbers = []
    for n in numbers:
        new_numbers.append(n + increment)
    return new_numbers
# We return the function as we do any other value
return add_increment

add5 = hof_add(5)
print(add5([23, 88]))   # [28, 93]
add10 = hof_add(10)
print(add10([23, 88]))  # [33, 98]

哪种方法是更好的实践?什么时候需要高阶函数?

标签: pythonfunctional-programminghigher-order-functions

解决方案


推荐阅读