59 lines
2.2 KiB
Markdown
59 lines
2.2 KiB
Markdown
|
# WTFunctional: Modifying your WTF-Count using functional programming #
|
||
|
|
||
|
## Content ##
|
||
|
|
||
|
* Dafunc? Understanding functional programming with Haskell.
|
||
|
+ no side-effects, no mutability => maintainability
|
||
|
+ recursion
|
||
|
+ functions as first class “objects”: i.e. C++, 5; is a valid statement
|
||
|
+ lambdas
|
||
|
+ lists, maps, filters, folds
|
||
|
=> readability, less code reproduction, threadsafety…
|
||
|
+ currying => just convenience
|
||
|
+ code example: Pythagoraian triangles.
|
||
|
* Phuncy: The pythonic way is functional!
|
||
|
+ Not strictly functional
|
||
|
+ recursion, fafco
|
||
|
+ lambda syntax
|
||
|
+ map, fold => example (sum of squares?)
|
||
|
- python lambda syntax: lambda a,b: a+b
|
||
|
- fold with reduce
|
||
|
- don't return lists, but iterators!
|
||
|
- Note: 2: map, filter, reduce
|
||
|
3: map, filter, functools.reduce()
|
||
|
```Removed reduce(). Use functools.reduce() if you really need it;
|
||
|
however, 99 percent of the time an explicit for loop is more
|
||
|
readable.```
|
||
|
Why use it? => Multi-processing!
|
||
|
```
|
||
|
a = list(range(10))
|
||
|
|
||
|
b = 0
|
||
|
for i in a:
|
||
|
b += i**2
|
||
|
print(b)
|
||
|
```
|
||
|
vs.
|
||
|
```
|
||
|
from functools import reduce
|
||
|
print(reduce(lambda x,y: x+y,map(lambda x: x**2,range(10))))
|
||
|
```
|
||
|
+ currying: not really, but binding via lambdas or functools.partial() or
|
||
|
https://mtomassoli.wordpress.com/2012/03/18/currying-in-python/
|
||
|
+ decorators!
|
||
|
+ still FP, has advantages and is heavily used, i.e. in genomics (works on
|
||
|
tons of lengthy lists)
|
||
|
* FunCtional++: On the fast lane
|
||
|
+ "Classical" C++ has some functional stuff, bust i.e. no lambdas (hardly usable)
|
||
|
+ Changed with the new C++11-standard
|
||
|
+ Buzzwords:
|
||
|
- `map` defines a Datatype in C++!
|
||
|
- lambdas in C++
|
||
|
```[](int x, int y) { return a<b;} ;```
|
||
|
[] can be used to capture variables, i.e. by reference or value
|
||
|
- `std::for_each` from `algorithm`: Apply `void fun(T &a)` to iterator
|
||
|
containing `T` values
|
||
|
- `std::transform` from `algorithm`: same as for_each, but stores return
|
||
|
value in another range
|
||
|
- `std::accumulate` from `numeric`: Wants binary operation, i.e. `std::minus<int>`
|