Python gains functional programming syntax via Coconut

The new language compiles directly to standard Python, so apps don't need a new interpreter to run

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.

Debugging plagued many of the languages that transpiled to JavaScript until sourcemaps came along to relate the transpiled code back to its source. Coconut provides something similar: If you pass a command-line switch to the Coconut compiler, it decorates every line of emitted Python code with a comment that refers back to the appropriate line in the Coconut source code.

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.

Copyright © 2016 IDG Communications, Inc.