Categories
Linux Programming

Thoughts on Coconut – the Compile-to-Python Functional Language Extension

Today I have been playing with the Coconut Language – see http://coconut-lang.org/ – so I thought I would put down some thoughts on using it, going through what I like and find interesting.

What Is Coconut?

So what is coconut? From their website:

Coconut is a functional programming language that compiles to Python.

One super-neat thing about coconut is that it’s completely Python-compatible – if you write a file in python that will happily run through the coconut compiler.

Also, what the coconut compiler outputs is valid python – so you can run it anywhere python runs.

These two points are very important – you aren’t learning an entirely new language, coconut is more like a set of extensions on top of python. You also don’t need to learn a new set of tools and libraries – want to get content from a URL? Use the requests library, as you normally would. How do you install coconut? Using pip, as you normally would. How do you separate out your libraries? Using venv as you normally would.

The Pipeline

My very favourite feature of coconut is the pipelines. The main one that I use is this: |>

What the pipeline does is to call the following function with the result of the previous function. This is great for filtering data, like this:

# Imagine we have a list of strings, and we want to do the following:
# * filter to only the ones that start with 'a'
# * then uppercase them all
# * and then print them

# Data:
data = [ 
  'and',
  'axe',
  'ark',
  'bat',
  'bag',
]

# Coconut version:
data |> filter$(s -> s.startswith('a')) |> map$(s -> s.upper()) |> list |> print

# Python version:
print(list(map(lambda s: s.upper(), filter(lambda s: s.startswith('a'), data))))

You can see from this trivial example that the flow of the data is much easier to read in the coconut version, as it flows smoothly from left to right. The python version instead “flows from the inside out”, making you count parentheses, and read the function list backwards. For more details, you can read the coconut docs on pipelines.

Lambda Syntax

Coconut adds a -> lambda syntax, which you can see in my example above. This one is a very small thing, and more about syntax preference, as both lambda styles do the same thing:

# Coconut
apiget = api -> requests.get(f'https://api.example.com/api/2/{url}')

# Python
apiget = lambda api: requests.get(f'https://api.example.com/api/2/{url}')

Leave a Reply

Your email address will not be published. Required fields are marked *