Coconut : Making python functional
These days there is talk of functional programming everywhere from JavaScript to c++ (yeah c++ now has lamda functions, higher order functions). But if you were someone who is writing python writing functional code (meaning without classes and using other functional concepts casually) every where is not a comfort you have without compromising the efficiency. So python has been lagging in this area.
But as always people with their awesomeness will figure out ways around it. One such effort is Coconut (yeah it is named after Monty python holy grail for those who remember it). Coconut is a language that compiles to python (don’t run away now). It is a super set of python. Meaning every python code is a valid Coconut code. More over it runs both python 2 and 3.
pip install coconut
Just to give you a taste of what it provides lets say you have a problem of finding largest element from the list and calculating its divisors.
in regular python you may do
def problem1(vals):
# calculate largest element of array
# find the divisor of the number
pass
Now that functions does more than one thing and may be hard to test if those things were complicated. In coconut you may write it as
(largest_elem...find_divisors)(vals)
that's more neat and it is more easily testable since each function does one simple thing (and if you were using lamdas to do this it might not look good as above and you have to worry about performance).
Coconut provides tail call optimization. Meaning you can go recursive as much as your heart content without worrying about performance reduction (someday python should have inbuilt tail call optimization ). and it also makes writing parallel programming more easy than you can think.
Here is the short list of features provided by Coconut
- pipeline-style programming
- prettier lamdas
- partial application
- pattern matching
- function composition
- destructing assignment
- infix function
- operator functions
- lazy list
- parallel programming
- tail call optimization
- algebraic data types
whats more you can start using coconut straight of the bat on your existing python code base. May be some day python may decide to include these features natively hope that day comes soon but till then lets use coconut like Monty python used coconut as a horse.