# 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`; `--watch` recompiles on changes); 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. For notebooks, `coconut --jupyter notebook` (or `lab`) uses the Coconut Jupyter kernel.
- `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, run `coconut file.coco --strict --no-write` (or pass a directory) to catch errors without writing output, adding `--pure` if the project uses it. Options in the `[tool.coconut]` table of the project's `pyproject.toml` (e.g. `strict = true`, `pure = true`, `target = "3.10"`) apply automatically. To see the Python a construct compiles to, run `coconut -c "code" --display` (or `coconut file.coco --no-write --display --quiet --target sys`).
- Look things up: `python -m coconut.lsp docs <name>` prints Coconut's documentation for any built-in, keyword, or operator (e.g. `docs collectby`, `docs |?>`), and `python -m coconut.lsp check <files or dirs>` reports errors plus lint warnings (`--mypy` to type check). `coconut --mcp` serves these tools over MCP. In Claude Code, the Coconut plugin (installed with `/plugin install coconut --marketplace evhub/coconut`, after installing `coconut[lsp]`) provides these tools and the Coconut language server, which reports errors after every edit to a `.coco` file; if you're in Claude Code without it, suggest it to the user.

## 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` blocks and expressions, pattern-matching function definitions, destructuring assignment) instead of chains of `if isinstance(...)`/indexing,
- models data with immutable **`data` types** instead of mutable classes, making updated copies of them with **update sections** (`obj |> (.pos.x += 1)`),
- uses **recursion** freely (tail calls are optimized automatically) and **lazy iterators** instead of materializing lists,
- uses Coconut's **built-ins** instead of hand-written helpers: `tap` is `ident$(side_effect=f)`, `curry` is `f$(x)`, `partition`/`group_by` is `collectby`, `pairwise` is `windowsof`, `chunks` is `groupsof`, `accumulate` is `scan`, and `memoize` and parallel `map` exist too (see "Built-ins instead of hand-written helpers"),
- 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 update sections (`obj |> (.pos.x += 1)` instead of `obj.pos.x += 1`), replace a loop that repeatedly updates some state with `iterate` (or `unfold`) over a function from one state to the next, 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` or `match`) instead of `isinstance` chains, tag strings, or flag attributes. Prefer `case def` to `addpattern def`, which redefines the function and so isn't pure; save `addpattern def` for adding a case to a function defined somewhere else.
- **Let the type checker check your matches.** A `match` (block or expression) or typed `case def` on a `case data` type must handle every variant; type checkers (`--mypy`, `--pyright`) report what's missing (e.g. `UnhandledCaseDataVariants[Square]`), so add the missing cases rather than a catch-all. End a `match` with `case _: assert_never(x)` (`from typing import assert_never`) to require it to handle every value of any type.
- **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 checkers check that every variant is handled
    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 |> (.balance += amount)          # an updated copy; account itself is unchanged
assert deposit(Account("me", 1), 2) == Account("me", 3)

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") |> fmap$(.+1) == Expected(81) and parse_port("x").error `isinstance` ValueError
assert parse_port("x").result_or(0) == 0     # also .unwrap(), .handle(ErrType, f), .map_error(f), .or_else(f)
```

## 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)
pow_of_2 = pow$(2)               # so there's no need for a curry helper (bare pow$ curries: (pow$)(2)(3) == 8)
square = pow$(?, 2)              # ? marks positional placeholders: x => pow(x, 2)
first = .[0]                     # x => x[0]; also .attr, .method(args), .attr.method(args), .[i][j]
third = .$[2]                    # .$[i] indexes/slices any iterator (e.g. a filter or generator), lazily
is_int = (. `isinstance` int)    # infix functions make partials too: x => isinstance(x, int)
reset = (.pos.x = 0)             # update section: x => a copy of x with x.pos.x set to 0
assert (+)(1, 2) == 3            # operator functions: (+), (==), (in), (not in), (is), (not), (and), (.) (getattr), (,) (tuple), (raise), etc.
f = def (x, y=1) => x + y        # statement lambda: allows defaults, patterns (def ((k, v)) => k), and statements (def (x) => y = x*2; y+1)
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: |?>, |?*>, |?**>
config = {"db": {"port": 5432}}
assert config.get("cache")?["port"] ?? 6379 == 6379 # ?[], ?., ?() short-circuit on None; a ?? b defaults
port = None
port ??= 8080                                       # assigns only if port is None
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

case def factorial:                          # a pattern-matching function, one case per line
    case(0) = 1
    case(int(n) if n > 0) = n * factorial(n - 1)

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

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

def describe(0) = "zero"                     # addpattern def adds a case to an existing
addpattern def describe(int()) = "an int"    #  pattern-matching function (prefer case def)

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 |> (.x = 0) == Point(0, 4)          # "modify" by making an updated copy (an update section)
assert p |> (.x *= 2) |> (.y -= 1) == Point(6, 3) and p == Point(3, 4)

data Segment(start: Point, end: Point)
seg = Segment(Point(0, 0), Point(1, 1))
assert seg |> (.end.x += 1) == Segment(Point(0, 0), Point(2, 1))   # nested paths copy each level
assert [seg] |> map$(.start = p) |> list == [Segment(p, Point(1, 1))]
assert {"a": [1, 2]} |> (.["a"][0] = 0) == {"a": [0, 2]}           # also tuples, lists, and dicts

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
case def depth:
    case(Leaf(_)) = 0
    case(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, as does
                                                      #  Interval(1, 3) |> (.hi = 0))

data Celsius(degrees: float):                         # custom constructors use __new__, calling
    def __new__(cls, degrees) = makedata(cls, float(degrees))   #  the base constructor with makedata
assert Celsius("1.5").degrees == 1.5

pt = (x=1, y=2)                                       # anonymous namedtuple, for one-off records
assert pt.x == 1 and pt == (1, 2)
```

## 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"

def tree_sum(t: Tree) -> int = match t:      # match expressions: the first matching case gives the value
    case Leaf(value): value                  #  (after =, after return, or as a function body)
    case Node(*children): children |> map$(tree_sum) |> sum
assert tree_sum(Node(Leaf(1), Node(Leaf(2), Leaf(3)))) == 6

reply = match "say hi".split():
    case ["quit"]: "bye"
    case ["say", *words]:                    # a case's body can be a block ending in its value
        text = " ".join(words)
        text + "!"
    else: "unknown"                          # with no else, no match raises MatchError
assert reply == "hi!"
```

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), `is expr` (identity 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)`, anonymous namedtuple patterns `(x=a, y=b)`, set patterns `s{1, 2, *_}` (sets containing these items; `m{...}` for multisets)

```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)
for Point(x, y) in pairs:                    # match for loops
    assert x < y

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 count() |> map$(.**2) |> takewhile$(.<20) |> list == [0, 1, 4, 9, 16]   # count() is infinite
it = reiterable(x * 2 for x in range(3))              # reiterable lets you iterate more than once
assert list(it) == list(it) == [0, 2, 4]
assert [1, 2, 3] |> fmap$(.*10) == [10, 20, 30]       # fmap preserves the container type
assert {"a": 1} |> fmap$(def ((k, v)) => (k, v + 1)) == {"a": 2}   # (on mappings, fmap maps over items)

# loops without reassignment: iterate(f, x) is x, f(x), f(f(x)), ... (lazy, and $[n] just applies f n times)
assert iterate((.*2), 1)$[10] == 1024
assert iterate((.*2), 1) |> dropwhile$(.<=1000) |> .$[0] == 1024
# unfold(f, seed): f(state) returns (value, next_state) to continue or None to stop
digits = unfold$(n => None if n == 0 else (n % 10, n // 10))
assert digits(1234) |> list == [4, 3, 2, 1]

@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)]
```

## Built-ins instead of hand-written helpers

Coconut has most of the functional toolkit built in, so check for a built-in before writing a helper:

```coconut
assert [1, 2] |> map$(ident$(side_effect=print)) |> list == [1, 2]   # tap/peek (prints 1, 2; handy for debugging pipes)
evens_odds = range(6) |> collectby$(x => x % 2 == 0)                 # partition/group_by: a defaultdict of lists
assert evens_odds[True] == [0, 2, 4] and evens_odds[False] == [1, 3, 5]
assert ["a", "bb", "c"] |> collectby$(len, value_func=.upper()) == {1: ["A", "C"], 2: ["BB"]}
assert "a bb cc" |> .split() |> collectby$(len, reduce_func=(+)) == {1: "a", 2: "bbcc"}         # group, then fold each group
assert "a b a" |> .split() |> mapreduce$(w => (w, 1), reduce_func=(+)) == {"a": 2, "b": 1}   # key_value_func returns (key, value)
assert range(4) |> windowsof$(2) |> list == [(0, 1), (1, 2), (2, 3)]                          # pairwise/sliding window (step=, fillvalue=)
assert range(5) |> groupsof$(2) |> list == [(0, 1), (2, 3), (4,)]                             # chunks/batches (fillvalue= pads)
assert range(1, 5) |> reduce$((*)) == 24 and range(1, 5) |> scan$((+)) |> list == [1, 3, 6, 10]   # fold; running totals
assert [[1], [2, [3]]] |> flatten$(levels=None) |> list == [1, 2, 3]                          # flattens one level by default
assert cartesian_product("ab", range(2)) |> list == [("a", 0), ("a", 1), ("b", 0), ("b", 1)]  # nested loops (repeat=n for powers)
assert flip(pow)(2, 3) == 9 and const(0)(1, 2) == 0 and call(pow, 2, 3) == 8              # flip args, constant function, apply
assert m{"a", "a", "b"}["a"] == 2 and all_equal([1, 1, 1])                                    # multiset (a Counter with set ops)

@memoize                                                             # functools.lru_cache(maxsize=None)
def fib(n) = n if n < 2 else fib(n - 1) + fib(n - 2)
assert fib(100) == 354224848179261915075
assert range(4) |> process_map$(pow$(?, 2)) |> list == [0, 1, 4, 9]  # parallel map over processes (args must pickle); thread_map for I/O
```

Also built in: `takewhile`, `dropwhile`, `count` (infinite and sliceable), `cycle`, `zip_longest`, `starmap`, `multi_enumerate`, `consume`, `override` (decorator: error if the method doesn't override anything), `and_then`/`and_then_await` (compose `async` functions), and `async_map`. `collectby` and `mapreduce` have parallel `.using_processes`/`.using_threads` versions, and `with process_map.multiple_sequential_calls():` reuses one pool across calls. Coconut's `map`, `zip`, and `enumerate` support `len` and indexing when their inputs do, and `map` and `zip` take `strict=True`.

## 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 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$[] = Iterable[int]
num: (+) &: (*) = 1                                    # &: intersects protocols; (+) supports +
type IntPairs = (int; int)[]                           # aliases need `type` to use Coconut's type syntax
def clamp[T <: float](x: T, lo: T, hi: T) -> T = max(lo, min(x, hi))   # type params (--strict wants <: for bounds)

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)
user_id = 7
assert dict(user_id=) == {"user_id": 7}      # keyword argument name elision: f(x=) is f(x=x)
assert [1, 2;; 3, 4] == [[1, 2], [3, 4]]     # multidimensional array literals (;; stacks rows, ; joins columns; numpy-aware)
final MAX_SIZE = 10                          # final: reassigning it is a compile error (--pure makes every name final)
```

## Common pitfalls

- An assignment function's block body must end in an expression: `def f(x) =` followed by a `match` statement or `if` statement on its own lines is an error. To compute a value by pattern matching, use a match expression (`def f(x) = match x:` with `case <pattern>: <value>` lines; see "Pattern matching"), or else a normal `def` with `return`. Match expressions only go after `=`, after `return`, or as a whole function body, never inside a larger expression (`1 + match x:` is an error).
- As in Python, sequence patterns (`[x, y]`, `[x, *rest]`, `case x, y:`) are 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 `(| 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 an updated copy with an update section, e.g. `obj |> (.pos.x = 0)` (which works for nested paths, unlike `._replace(...)`).
- Update sections need their own parentheses, like `(.+1)`: `map(.hp -= 1, xs)` is a syntax error, so write `xs |> map$(.hp -= 1)` (the parentheses of a call with just the update section count). They never mutate anything, so `(.items += [x])` sets `items` to a new list, `old.items + [x]`.
- Exhaustiveness errors only show up when type checking (`--mypy`, `--pyright`, or the language server's type checking), never in a plain compile. Guarded cases (`case Circle(r) if r > 0`) don't count as handling anything, and matches using sequence, mapping, or string patterns aren't checked. Under `--pure`, every multi-case `match` (including match expressions) and typed `case def` must be total, so give guarded cases a final unguarded fallback.
- `--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, pipeline, or `iterate`/`unfold`, 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.
- In an operator partial, everything after the operator is its operand: `(.%2==0)` is `x => x % (2==0)`, not `x => x % 2 == 0`. Such ambiguous partials are deprecated (a warning, or an error under `--strict`), so compose instead (`(.%2) ..> (.==0)`), use a lambda, or parenthesize the operand (`(. % (2==0))`) if that's what you mean.
- Coconut's `map`/`filter`/`zip` are lazy (like Python 3), so convert with `|> list` or `|> tuple` when you need a concrete sequence.
