Skip to content

Instantly share code, notes, and snippets.

@opethe1st
Last active March 15, 2019 13:04
Show Gist options
  • Save opethe1st/d86ce321e6a80c27af4ac5ed31a918e5 to your computer and use it in GitHub Desktop.
Save opethe1st/d86ce321e6a80c27af4ac5ed31a918e5 to your computer and use it in GitHub Desktop.
How to express summation
"""
How do we express the concept of summing values of a function over a set of values?
∑f(n) with n ∈ A
"""
array = range(29)
f = lambda x: x**2
# imperative
total = 0
for item in array:
total += f(item)
print(total)
# functional
total = sum(map(f, A)) # succint and brilliant!
# can also inline
total = sum(map(lambda x: x**2, range(29))
"""
Why so brilliant?
because it encapsulates what could change very well. You can replace the function with something else or the range with another iterable
what about if we didn't want to sum but we want to find the product?
All that has to change is the operation we want to use to combine - from an addition to a mulplication. What's common between
sum and product is that they are both accumulations (reductions too? - python has reduce) but with different binary operators.
So a product version will look like this below
"""
from functools import reduce # it is a shame this has to be imported
# observe same terms both the "combinator" - (+/*) is different.
product = reduce(lambda x: x*y, map(lambda x: x**2, range(29))
"""
What's the the big idea? This is just a different way of accomplishing the same thing and all ways are valid, right?
Well, one way captures what you are trying to do more succintly and relies on existing patterns. It also encapsulates what
changes very well, which is a vital quality in a programs that are going to be very versatile.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment