data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def square(x): return x ** 2 def iseven(n): return n % 2 == 0 def add(x, y): return x + y def mul(x, y): return x * y def lesser(x, y): if x < y: return x else: return y def greater(x, y): if x > y: return x else: return y # map works like this map(square, data) # In this way it's like numpy's broadcasting operators import numpy as np X = np.arange(1, 11) X**2 def fib(i): if i in (0, 1): return i else: return fib(i - 1) + fib(i - 2) map(fib, data) # Normally we would perform this in the following way result = [] for item in data: result.append(fib(item)) result # looking at the function above gives us a good pattern for how to define `map` # We just abstract out the function `fib` for a user input # `map` is easy to define def map(fn, sequence): result = [] for item in sequence: result.append(fn(item)) return result map(str.upper, ['Alice', 'Bob', 'Charlie']) [fib(i) for i in data] [name.upper() for name in ['Alice', 'Bob', 'Charlie']] filter(iseven, data) from sympy import isprime # Only works if you have the sympy math library installed filter(isprime, data) def filter(predicate, sequence): result = [] for item in sequence: if predicate(item): result.append(item) return result def sum(sequence): result = 0 for item in sequence: # reult = result + item result = add(result, item) return result def min(sequence): result = 99999999999999 # a really big number for item in sequence: # result = result if result < item else item result = lesser(result, item) return result def product(sequence): result = ? for item in sequence: result = ?(result, item) return result assert product([2, 3, 10]) == 60 def reduce(...): ... reduce(add, data, 0) reduce(mul, data, 1) reduce(lesser, data, 10000000) reduce(greater, data, -100000000) reduce(add, data, 0) reduce(lambda x, y: x + y, data, 0) # Define `add` on the fly sum = lambda data: reduce(add, data, 0) min = lambda data: reduce(lesser, data, 99999999999) max = lambda data: reduce(greater, data, -999999999999) sum(data) product = ... assert product([2, 3, 10]) == 60 filter(iseven, data) from toolz import groupby groupby(iseven, data) groupby(isprime, data) groupby(lambda n: n % 3, data) groupby(len, ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank']) likes = """Alice likes Chocolate Bob likes Chocolate Bob likes Apples Charlie likes Apples Alice likes Peanut Butter Charlie likes Peanut Butter""" tuples = map(lambda s: s.split(' likes '), likes.split('\n')) tuples groups = groupby(lambda x: x[0], tuples) groups from toolz import valmap, first, second valmap(lambda L: map(second, L), groups) valmap(lambda L: map(first, L), groupby(lambda x: x[1], tuples)) from toolz.curried import map, valmap, groupby, first, second, get, curry, compose, pipe tmap = curry(compose(tuple, map)) pipe(tuples, groupby(second), valmap(tmap(first))) valmap(tmap(first), groupby(second, tuples)) f = compose(valmap(tmap(first)), groupby(second)) f(tuples)