# Coconut

> Coconut is a functional programming language that compiles to Python. All valid Python 3 code is valid Coconut, and Coconut adds pipes, partial application, pattern matching, algebraic data types, lazy iterators, tail call optimization, and more. Compiled code runs on any Python version (2.7 and 3.x).

This is a condensed guide to writing idiomatic Coconut, intended for AI coding assistants. Full documentation: https://coconut.readthedocs.io/en/latest/DOCS.html (tutorial: https://coconut.readthedocs.io/en/latest/HELP.html). Run `coconut --ai-docs` to print this guide. For a much larger collection of examples of what Coconut can do, see the test suite's https://github.com/evhub/coconut/blob/develop/coconut/tests/src/cocotest/agnostic/util.coco.

## Working with Coconut code

- Source files end in `.coco`. **Compiled `.py` files are generated: always edit the `.coco` source, never the compiled `.py` file.** Compiled files start with a comment saying which source file they were compiled from, and every compiled line ends with a `# <n> (line in Coconut source)` comment pointing back to the source line.
- Compile: `coconut src_dir dest_dir` (or `coconut file.coco`); compile and run: `coconut-run file.coco`; run code directly: `coconut -c "code"`; type check: add `--mypy` (or `--pyright`); target a Python version: `--target 3.11` (default output is universal).
- Importing `coconut.api` enables automatic compilation of `.coco` files on import. For tests, `pytest -p coconut.pytest_plugin` collects `test_*.coco` files.
- `coconut --strict` enables style checks; fix what it reports by restructuring the code rather than suppressing it with `# NOQA`. `coconut --pure` additionally enforces functional purity (no reassignment or mutation); it's optional, so use it when the project enables it or the user asks for it.
- Check your work: after editing `.coco` files, compile them with `coconut file.coco --strict --no-write` (or pass a directory) to catch errors without writing output, adding `--pure` if the project uses it. Options set in the `[tool.coconut]` table of the project's `pyproject.toml` (e.g. `strict = true`, `pure = true`, `target = "3.10"`) apply automatically. When you're unsure what a construct does, look at the Python it compiles to with `coconut file.coco --no-write --display --quiet --target sys` (or `coconut -c "code" --display`).

## Writing idiomatic Coconut

Prefer Coconut's functional features over Python-style imperative code. Good Coconut code:
- passes data through **pipelines** (`|>`) of small functions instead of nesting calls or building lists in loops,
- uses **implicit partials** (`.attr`, `.method()`, `.[i]`, `(.+1)`) and **operator functions** (`(+)`, `(==)`) instead of lambdas where possible,
- builds simple transformations **point-free** by composing functions (`..>`, `lift`) rather than writing wrapper functions,
- defines functions with **assignment function syntax** (`def f(x) = ...`) when the body is a single expression,
- uses **pattern matching** (`match`/`case`, pattern-matching function definitions, destructuring assignment) instead of chains of `if isinstance(...)`/indexing,
- models data with immutable **`data` types** instead of mutable classes,
- uses **recursion** freely (tail calls are optimized automatically) and **lazy iterators** instead of materializing lists,
- avoids reassigning variables and mutating objects (`--pure` mode can enforce this).

```coconut
# Python-style (works, but not idiomatic)
def total_lengths(words):
    result = 0
    for w in words:
        if len(w) > 2:
            result += len(w)
    return result

# idiomatic Coconut
def total_lengths(words) = words |> map$(len) |> filter$(.>2) |> sum
```

## Style standard

Write code that reads at a glance:
- **Expressions, not steps.** Most functions should be a single `def f(...) = expr`. Name intermediate values in a `where:` block or a short block body rather than reassigning a variable step by step.
- **One stage per line.** Put a pipeline with more than about three stages in parentheses, one `|>` stage per line, so it reads top to bottom.
- **Avoid mutation.** Build new values with comprehensions, pipelines, `fmap`, `reduce`/`scan`, and `._replace` on `data` types, and keep mutable state at a program's edges (I/O, caches). (Under `--pure`, mark any such mutation with `# NOQA` and a comment saying why.)
- **Data first.** Model the domain with `data` types, and with `case data` sum types when a value is one of several alternatives, and write functions on them with pattern matching (`case def`, `match`, or `addpattern def`) instead of `isinstance` chains, tag strings, or flag attributes.
- **Types on top-level definitions**, written in Coconut's type syntax (`int[]`, `int?`, `int -> str`, `(int; str)`), checked with `--mypy` when it's available.
- **Errors as values** for expected failures: return `Expected` (or `Optional`) values, wrap raising calls in `safe_call`, and chain with `.and_then`/`fmap`; keep `try`/`except` for truly exceptional cases.
- **Lazy in the middle, concrete at the edges:** keep iterators lazy through a pipeline and materialize (`|> list`, `|> tuple`) only where a concrete value is needed.
- **Partials over lambdas:** use `.attr`, `.method()`, `.[i]`, and operator functions; when a lambda grows beyond a short expression, make it a named `def`.

```coconut
# before: imperative Python in a .coco file
def top_words(text, n):
    counts = {}
    for word in text.split():
        word = word.lower().strip(".,!?")
        if word:
            counts[word] = counts.get(word, 0) + 1
    ranked = sorted(counts.items(), key=lambda kv: -kv[1])
    return [w for w, c in ranked[:n]]

# after: idiomatic Coconut (passes --strict, --pure, and mypy)
from collections import Counter

def top_words(text: str, n: int) -> str[] = (
    text.split()
    |> map$(.lower())
    |> map$(.strip(".,!?"))
    |> filter$(bool)
    |> Counter
    |> .most_common(n)
    |> map$(.[0])
    |> list
)
assert top_words("The cat saw the cat. The end!", 2) == ["the", "cat"]
```

```coconut
import math

case data Shape:                             # a sum type: a Shape is exactly one of these variants
    case Square(side: float)
    case Circle(radius: float)

case def area:
    type(shape: Shape) -> float
    case(Square(side)) = side ** 2
    case(Circle(radius)) = math.pi * radius ** 2
assert area(Square(2)) == 4

data Account(owner: str, balance: int)

def deposit(account: Account, amount: int) -> Account =
    account._replace(balance=account.balance + amount)

def check_port(port: int) -> Expected[int] =
    Expected(port) if 0 < port < 65536 else Expected(error=ValueError(f"bad port: {port}"))

def parse_port(s: str) -> Expected[int] = safe_call(int, s).and_then(check_port)
assert parse_port("80") == Expected(80) and parse_port("x").error `isinstance` ValueError
```

## Lambdas, partials, and operator functions

```coconut
add = (x, y) => x + y            # lambda (=> is preferred; old -> syntax is deprecated)
inc = (.+1)                      # implicit partial: same as x => x + 1
upper_all = map$(.upper())       # partial application with $: f$(a) is functools.partial(f, a)
square = pow$(?, 2)              # ? marks positional placeholders: x => pow(x, 2)
first = .[0]                     # x => x[0]; also .attr and .method(args)
assert (+)(1, 2) == 3            # operator functions: (+), (*), (==), (in), (not in), (is), (.), etc.
f = def (x, y=1) => x + y        # statement lambda (supports default args, multiple statements)
sign = (=> if _ > 0 then 1 else if _ < 0 then -1 else 0)   # implicit lambda (argument is _), if/then/else expression
assert [-5, 0, 5] |> map$(sign) |> list == [-1, 0, 1]
```

## Pipes and composition

```coconut
assert range(5) |> map$(x => x * 2) |> filter$(.>2) |> list == [4, 6, 8]
assert (1, 2) |*> add == 3                          # |*> unpacks positional args
assert dict(x=1, y=2) |**> ((x, y) => x - y) == -1  # |**> unpacks keyword args
assert str <| 1 == "1"                              # backward pipes: <|, <*|, <**|
assert None |?> (.+1) is None                       # None-aware pipes: |?>, |?*>, |?**>
f = (.+1) ..> (.*2)                                 # forward composition: f(3) == 8
g = (.*2) <.. (.+1)                                 # backward composition (also ..): g(3) == 8
xs = [3, 1, 2]
xs |>= sorted                                       # in-place pipe: xs = sorted(xs)
```

Pipes bind more loosely than arithmetic but more tightly than comparisons, so `x + 1 |> f == y` means `f(x + 1) == y`. Inside a pipe, `x |> await` awaits, and `x |> (name := .)` binds the intermediate value.

## Point-free style

Composition (`..>`, `..*>` to unpack into the next function) together with `lift` lets you define functions without naming their arguments:

```coconut
sum_evens = range ..> filter$((.%2) ..> (.==0)) ..> sum
assert sum_evens(10) == 20

min_and_max = lift(,)(min, max)              # lift(f)(g, h)(x) == f(g(x), h(x))
assert min_and_max([3, 1, 2]) == (1, 3)
add_pair = lift_apart(+)(len, abs)           # lift_apart(f)(g, h)(x, y) == f(g(x), h(y))
assert add_pair("ab", -3) == 5

maxdiff = (                                  # largest later-minus-earlier difference
    ident `lift(zip)` scan$(min)             #  (x => zip(x, scan(min, x)))
    ..> starmap$(-)
    ..> filter$(.!=0)
    ..> reduce$(max, ?, -1)
)
assert maxdiff([7, 1, 5, 4]) == 4

dict_zip = (,) ..> map$(.items()) ..> flatten ..> collectby$(.[0], value_func=.[1])
assert dict_zip({"a": 1}, {"a": 2, "b": 3}) == {"a": [1, 2], "b": [3]}
```

## Function definitions

```coconut
def square(x) = x ** 2                       # assignment function: body is a single expression

def norm(x, y) =                             # assignment function with a block body:
    sq = x**2 + y**2                         #  the last line must be an expression
    sq ** 0.5

def factorial(0) = 1                         # pattern-matching function definition
addpattern def factorial(int(n) if n > 0) = n * factorial(n - 1)   # add another case

def head_tail([x] + xs) = (x, xs)            # patterns in arguments

def fact(0, acc=1) = acc                     # patterns can have defaults and guards
addpattern def fact(int() as n, acc=1 if n > 0) = fact(n - 1, acc * n)

case def my_min[T]:                          # many cases at once, with type parameters and
    type(xs: T[]) -> T                       #  optional (overloaded) type signatures
    case([x]) = x
    case([x] + xs) = my_min(x, my_min(xs))
    type(x: T, y: T) -> T
    case(x, y if x <= y) = x
    case(x, y) = y

def count_down(n):                           # tail calls are optimized, so deep recursion is fine
    if n <= 0:
        return "done"
    return count_down(n - 1)
```

Tail call optimization only applies to `return f(...)` where the returned value is directly a call (not `f(...) if c else x` and not `f(...) + 1`). A pattern-matching function that fails to match raises `MatchError`.

## Data types

```coconut
data Point(x: float, y: float):              # immutable, hashable, with __eq__/__repr__ (a namedtuple)
    def __add__(self, other: Point) -> Point = Point(self.x + other.x, self.y + other.y)
    def norm(self) -> float = (self.x**2 + self.y**2) ** 0.5

p = Point(3, 4)
assert p.norm() == 5 and p + Point(1, 1) == Point(4, 5)
assert p._replace(x=0) == Point(0, 4)        # "modify" by creating a new value

case data Tree:                              # algebraic data types: case data defines a sum type
    case Leaf(value)                         #  whose variants are data types
    case Node(*children)                     # a starred field collects the remaining arguments
    def size(self) -> int = depth(self) + 1  # methods shared by all the variants
def depth(Leaf(_)) = 0
addpattern def depth(Node(*children)) = children |> map$(depth) |> max |> (.+1)
assert depth(Node(Leaf(1), Node(Leaf(2), Leaf(3)))) == 2
assert Leaf(1) `isinstance` Tree and Node(Leaf(1)).size() == 2

data Interval(int() as lo, int() as hi if hi >= lo)   # patterns validate constructor arguments
assert Interval(1, 3).hi == 3                         #  (Interval(3, 1) raises MatchError)
```

## Pattern matching

```coconut
def describe(obj):
    match obj:
        case Point(x, y) if x == y:          # data type patterns, with guards
            return "diagonal point"
        case {"type": "point", "x": x, **_}: # dict patterns (**_ allows extra keys)
            return f"point at {x}"
        case []:
            return "empty"
        case [x]:                            # sequence patterns
            return f"one: {x}"
        case [x, *rest]:                     # star patterns
            return f"many, starting with {x}"
    return "unknown"
```

Python 3.10 `match`/`case` syntax works on every target version. Other pattern forms:
- `[x] + xs` / `xs + [x]` (head/tail and init/last splits), `"prefix_" + rest` (string splits), `(| x, y |)` / `(| x, *rest |)` (lazy lists: match any iterable), `[x] :: rest` (any iterable, lazily)
- `int(n)` / ``n `isinstance` int`` (type checks), `x if x > 0` (guards), `pat as name`, `pat1 | pat2`, `==expr` (equality checks), `(f) -> pat` (view patterns: match `f(item)` against `pat`)
- data patterns `Point(x=x, **rest)` (`**rest` collects the remaining fields), class patterns `class C(a, b)`

```coconut
match (x, y) in (1, 2):                      # one-line match with else
    print(x + y)
else:
    print("no match")

[first] + rest = [1, 2, 3]                   # destructuring assignment (raises MatchError on failure)
{"name": name, **_} = {"name": "x", "age": 3}

pairs = [Point(1, 2), Point(3, 4)]
xs = [x for Point(x, y) in pairs if y > 2]   # match comprehensions (raise MatchError on non-matches)

def first_twin(_ + [p, (.-2) -> p] + _) = (p, p + 2)  # search pattern with a view pattern:
assert first_twin([2, 3, 5, 7, 11, 13]) == (3, 5)     #  (.-2) -> p matches items equal to p + 2
match key + "=" + value in "name=coconut":            # string search patterns
    assert (key, value) == ("name", "coconut")
```

## Iterators and laziness

```coconut
nums = (| 1, 2, 3 |)                                  # lazy list
def naturals(n=0) = (n,) :: naturals(n + 1)           # :: lazily chains iterators (infinite is fine)
assert naturals()$[:5] |> list == [0, 1, 2, 3, 4]     # $[...] slices any iterator lazily
assert range(10) |> groupsof$(3) |> map$(list) |> list == [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
assert range(4) |> windowsof$(2) |> list == [(0, 1), (1, 2), (2, 3)]
assert range(5) |> reduce$((+)) == 10                 # reduce and scan are built in
assert range(4) |> scan$((+)) |> list == [0, 1, 3, 6]
assert [[1, 2], [3]] |> flatten |> list == [1, 2, 3]
assert [1, 2, 3] |> fmap$(.*10) == [10, 20, 30]       # fmap preserves the container type
assert ["a", "bb", "c"] |> collectby$(len) == {1: ["a", "c"], 2: ["bb"]}

@recursive_generator                                  # memoizes so self-reference is efficient
def fibs() = (0, 1) :: map((+), fibs(), fibs()$[1:])
assert fibs()$[:8] |> list == [0, 1, 1, 2, 3, 5, 8, 13]

def odd_primes(p=3) = (p,) :: filter((=> _ % p != 0), odd_primes(p + 2))
def primes() = (2,) :: odd_primes()
def twin_primes(_ :: [p, (.-2) -> p] :: ps) =         # :: patterns lazily match infinite iterators
    [(p, p + 2)] :: twin_primes([p + 2] :: ps)
assert twin_primes(primes())$[:3] |> list == [(3, 5), (5, 7), (11, 13)]
```

Other useful built-ins: `takewhile`, `dropwhile`, `count`, `cycle`, `cartesian_product`, `multi_enumerate`, `consume`, `reiterable`, `ident`, `const`, `flip`, `lift`, `memoize` (decorator), `recursive_generator`, `process_map`/`thread_map` (parallel map), `mapreduce`, `multiset`, `safe_call`/`Expected` (error handling without exceptions). Coconut's `map`, `zip`, and `enumerate` support `len` and indexing when their inputs do.

## Other features

```coconut
result = a + b where:                        # where: local definitions after the expression
    a = 1
    b = 2

result = where:                              # or with the result at the end
    a = 1
    a + 1

def mod_(a, b) = a % b
assert 5 `mod_` 3 == 2                       # backticks: infix function call

operator <$                                  # custom operators
def x <$ xs = fmap((=> x), xs)
assert 0 <$ [1, 2] == [0, 0]
def (a: int) `divides` (b: int) -> bool = b % a == 0   # infix function definition
assert 3 `divides` 12

def make_getters() =
    getters = []
    for i in range(3):
        copyclosure def get() = i            # copyclosure captures the current value of i
        getters.append(get)
    getters
assert [get() for get in make_getters()] == [0, 1, 2]

class Tally:
    count = 0
def Tally.inc(self) -> Tally =               # define a method outside its class
    self.count += 1
    self
assert Tally().inc().inc().count == 2

def safe_div(x, y) = safe_call((=> x / y))   # Expected(result) or Expected(error=...)
assert safe_div(4, 2) |> fmap$(.*10) == Expected(20.0)
assert safe_div(1, 0).error `isinstance` ZeroDivisionError

def first(xs: int[]) -> int? = xs[0] if xs else None   # int[] = Sequence[int], int? = Optional[int]
def apply(f: int -> str, x: int) -> str = f(x)         # int -> str = Callable[[int], str]
pair: (int; str) = (1, "a")                            # (int; str) = Tuple[int, str]
def lens(xs: int$[]) -> int = xs |> map$(.bit_length()) |> sum   # int$[] = Iterator[int]
num: (+) &: (*) = 1                                    # &: intersects protocols; (+) supports +

lazy import json                             # PEP 810 lazy imports, on every Python version
assert json.loads("[1]") == [1]
def double(x) = x * 2
assert double 3 == 6                         # implicit function application: f x is f(x)
```

## Common pitfalls

- An assignment function's block body must end in an expression: `def f(x) =` followed by a `match` statement or `if` statement is an error. Use a normal `def` with `return` instead.
- Write sequence patterns (`[x, y]`, `[x, *rest]`, `case x, y:`) as if they follow Python's rules: they're meant to match only non-string sequences. Coconut still lets them match strings, and lets star and unparenthesized tuple patterns match any iterable, but that's deprecated: such matches emit a `CoconutWarning` and will fail in Coconut v4. To match any iterable, use lazy list patterns `(| x, *rest |)` or `[x] :: rest`; to match strings, use string patterns like `"prefix_" + rest`.
- Sequence patterns also match `data` types (which are tuples), so put data type patterns before general sequence patterns in a `match`.
- Coconut keywords like `data`, `match`, `case`, `where`, and `addpattern` can still be used as names, but writing `match[a, b] = x` is a subscript assignment to a variable named `match`. Since normal assignment takes precedence over destructuring assignment, use patterns that aren't valid Python assignment targets (e.g. `[first] + rest = xs`) when you need destructuring.
- To use a name that conflicts with a Coconut keyword or would be flagged by `--strict`, escape it with a backslash: `\data`, `\match`.
- `f x` is a function call (implicit application) and `2 x` is `2 * x` (implicit coefficients), so a missing comma doesn't cause an error: `foo(1, a b)` is `foo(1, a(b))`. When code compiles but behaves oddly, check argument lists for missing commas.
- Precedence: pipes bind more loosely than arithmetic but more tightly than comparisons, so `x |> f == y` is `(x |> f) == y`. A lambda in a pipe extends to the end of the pipe, so `xs |> x => x + 1 |> print` is `xs |> (x => x + 1 |> print)`; parenthesize lambdas in pipes.
- `data` types are immutable (they're tuples): instead of assigning to an attribute, make a new value with `._replace(...)`.
- `--pure` treats loop variables as assignments, so reassigning one in the loop body, or reusing the same loop variable name for two loops in one scope, is flagged; prefer a comprehension or pipeline, or use distinct names.
- Implicit partials can't chain calls: `map$(.lower().strip())` is a syntax error. Use one stage per method (`|> map$(.lower()) |> map$(.strip())`) or a named function.
- Coconut's `map`/`filter`/`zip` are lazy (like Python 3), so convert with `|> list` or `|> tuple` when you need a concrete sequence.
