Calvin Deutschbein
School of Computing & Information Sciences
Willamette University
from functools import reduce
func_sum = lambda lst: reduce(lambda x, y: x + y, lst)
func_sum(range(16, 65536, 256)), sum(range(16, 65536, 256))
(8359936, 8359936)
start, _, end = time(), func_sum(range(16, 65536, 256)), time()
print('functional', end - start)
start, _, end = time(), sum(range(16, 65536, 256)), time()
print('built-in__', end - start)
functional 0.025910377502441406
built-in__ 1.1205673217773438e-05
abc = ['a', 'b', 'c']
print(func_sum(abc))
try:
sum(abc)
except:
print("sum likes numbers, even though + doesn't care")
reduce(lambda x, y: x + y, abc)
foldl_red = reduce
from operator import *
foldl_red(add, abc), foldl_red(sub, range(0, 4))
('abc', -6)
foldl = lambda f, lst: f(foldl(f, lst[:-1]), lst[-1]) if len(lst) > 1 else lst[0]
foldr = lambda f, lst: f(lst[0], foldr(f, lst[1:])) if len(lst) > 1 else lst[0]
def foldr(f, lst):
ret = lst[-1]
for ele in lst[-2::-1]:
ret = f(ele, ret)
return ret
def foldl(f, lst):
ret = lst[0]
for ele in lst[1:]:
ret = f(ret, ele)
return ret
print('1 - (2 - 3) =', 1 - (2 - 3), ', (1 - 2) - 3 =', (1 - 2) - 3)
print('foldr(-, [1, 2, 3]) =', foldr(sub, [1, 2, 3]), ', foldl(-, [1, 2, 3]) =', foldl(sub, range(1, 4)))
1 - (2 - 3) = 2 , (1 - 2) - 3 = -4
foldr(-, [1,2,3]) = 2 , foldl(-, [1,2,3]) = -4
total = 0 # sum is a name-space collision
[total := add(total, ele) for ele in range(10)]
def foldl(f, lst):
ret = lst[0]
return [ret := f(ret, ele) for ele in lst[1:]][-1]
def foldr(f, lst):
ret = lst[-1]
return [ret := f(ele, ret) for ele in lst[-2::-1]][-1]
> foldl f z [] = z
> foldl f z (x:xs) = let z' = z `f` x
> in foldl f z' xs
foldl_zed = lambda f, z, xs: [z := f(z, x) for x in xs][-1]
foldl_zed(add, '', abc), foldl_zed(sub, 0, range(1,4)), reduce(sub, range(0,4))
('abc', -6, -6)
λ foldl (-) 0 [1,2,3]
-6
:: Num b => b
λ