# Functional patterns

## Functional core, effectful shell

```text
input = read_input()                 # effect
parsed = parse(input)                # pure
decision = apply_rules(parsed, cfg)  # pure
output = render(decision)            # pure
write_output(output)                 # effect
```

## Explicit dependencies

```text
is_expired(record, now):
    return record.expires_at < now
```

Acquire `now` once in the shell when a workflow needs one consistent instant.

## Immutable transformation

```text
activate(user):
    return copy(user, status = "active")
```

Use the language's copy or update syntax, persistent collections, or a builder that freezes at the boundary.

## Declarative collection pipeline

```text
eligible = filter(is_eligible, accounts)
balances = map(project_balance, eligible)
total = sum(balances)
```

Fuse stages or use a loop when intermediate allocations matter.

## Higher-order configuration

```text
minimum_score(threshold):
    return candidate => candidate.score >= threshold
```

Use partial application only when the configured function will be reused.

## Pure state transition

```text
transition(state, event):
    next_state = derive_next_state(state, event)
    commands = derive_commands(state, event, next_state)
    return next_state, commands
```

Let the shell execute the commands.

## Failure as data

```text
parse_order(raw) -> Result<Order, ParseError>
price(order, catalog) -> Result<Money, PricingError>
```

## Memoization

Memoize only when the function is pure for the full key, repeated work is expensive, memory growth is bounded, and sensitive results cannot cross authorization boundaries.

## Localized mutation

```text
build_index(items):
    mutable = new_builder()
    for item in items:
        mutable.add(item.key, item.value)
    return mutable.freeze()
```

Keep the mutation private and test that inputs remain unchanged.
