Many Python fans have longed for the language to adopt functional programming features. Now they can get those features without having to switch to a new Python implementation.
Coconut, a newly developed open source dialect of Python, provides new syntax for using features found in functional languages like Haskell and Scala. Programs written in Coconut compile directly to vanilla Python, so they can be run on whatever Python interpreter is already in use.
Many of the new features exposed by Coconut involve more elegant and readable ways to do things Python already does. "Pipeline-style programming," for example, allows the arguments for a function to be submitted to the function with separate syntax. For example,
print("Hello, world!") would be written as
"Hello, world!" |> print. Lambdas, or anonymous functions in Python, can be written more clearly, such as
(x) -> x**2 instead of
lambda x: x**2.
One convenient behavior not available through Python's native syntax, but which is found in many other modern languages, is pattern matching. Values can be tested for a match against a defined pattern, and in the event of a match, variables can be bound from the match and submitted as arguments to a function.
If this sounds like the way regular expressions work, that's not far from the mark, but Coconut allows matching for more than just string expressions. For example, a list of incoming objects could be matched against a list of prospective data types.
Coconut's creators want the language to be a logical extension to Python, not a replacement for it. All valid Python apps are also valid Coconut apps, and so Coconut can draw on the existing roster of libraries and C extensions without much, if any alteration.
Sign up for CIO Asia eNewsletters.