|
8 | 8 | # Motivation |
9 | 9 | [Blog post about ScalaFunctional](http://pedrorodriguez.io/2015/03/14/chain-functional-programming-in-python-2/) |
10 | 10 |
|
11 | | -Having programmed functionally in Scala and now using Python I missed the syntax/style for it from Scala. Most of that can be summed up by comparing the Scala style vs Python style for taking a list, filtering on a criteria, mapping a function to it, then reducing it. Below is a comparison of the default Python style and the Scala inspired style that ScalaFunctional uses. |
| 11 | +`ScalaFunctional` exists to make functional programming with collections easy and intuitive in Python. It borrows the functional programming APIs from Scala and Apache Spark. |
| 12 | + |
| 13 | +To demonstrate the different style of Python map/filter/reduce, list comprehensions, and `ScalaFunctional`, the code block below does the same thing in all three: manipulate a list of numbers to compute a result. |
12 | 14 |
|
13 | 15 | ```python |
14 | 16 | l = [1, 2, -1, -2] |
15 | | -f = lambda x: x > 0 |
16 | | -g = lambda x: x * 2 |
17 | | -q = lambda x, y: 2 * x + y |
18 | 17 |
|
19 | 18 | # Python style |
20 | | -reduce(q, map(g, filter(f, l))) |
| 19 | +reduce(lambda x, y: x * y, map(lambda x: 2 * x, filter(lambda x: x > 0, l))) |
21 | 20 |
|
22 | 21 | # Python list comprehension |
23 | | -reduce(q, [g(x) for x in l if f(x)]) |
| 22 | +reduce(lambda x, y: x * y, [2 * x for x in l if x > 0]) |
24 | 23 |
|
25 | 24 | # ScalaFunctional style |
26 | 25 | from functional import seq |
27 | | -seq(l).filter(f).map(g).reduce(q) |
| 26 | +seq(l).filter(lambda x: x > 0).map(lambda x: 2 * x).reduce(lambda x, y: x * y) |
| 27 | +``` |
28 | 28 |
|
| 29 | +Although a trivial example, the real power of `ScalaFunctional` is composing transformations not available natively in Python. For example, the very common word count example is easy: |
| 30 | +``` |
29 | 31 | # ScalaFunctional word count |
30 | 32 | l = seq("the why the what of word counting of english".split(" ")) |
31 | 33 | l.map(lambda word: (word, 1)).reduce_by_key(lambda x, y: x + y) |
|
0 commit comments