From argument patterns to pattern matching

With |> already in use in Nix, I’ve been thinking about another small language extension.

Nix already has partial functions at the argument-matching level: { a, ... }: ... accepts some arguments and rejects others. Adding just two trivial builtins would let us compose these into pattern matching.

1. builtins.functionDefinedAt: Ask whether a function accepts an argument

Introduce builtins.functionDefinedAt f x, which checks the argument pattern without evaluating the body:

functionDefinedAt ({ name, ... }: name) {}                    # false
functionDefinedAt ({ name, ... }: name) { name = "Alice"; }   # true
functionDefinedAt ({ name, ... }: name) { name = throw "x"; } # true
functionDefinedAt (x: throw "not called") 42                  # true

This is about matching the first argument, not predicting whether the function will evaluate successfully. Defaults and unused fields should remain lazy.

For callable sets, we could use a convention: an optional __defined = x: ... predicate describes their domain.

2. builtins.functionOrElse: Combine partial functions

Introduce builtins.functionOrElse f g: try f if its argument matches; otherwise use g.

Using the proposed domain check, the combinator itself can be written in pure Nix:

functionOrElse = f: g: {
  __functor = self: x:
    if functionDefinedAt f x then f x else g x;

  __defined = x:
    functionDefinedAt f x || functionDefinedAt g x;
};

Order matters: the first matching branch wins. An error inside a selected body remains an error; it does not cause fall-through.

(If checking and then destructuring the argument again looks wasteful, an apply-or-fallback primitive, with an __applyOrElse hook on functors, can do the matching once - the idea is from Scala’s PartialFunction. The same applies to guards described below.)

3. Give it an operator

Let f | g mean functionOrElse f g. Combined with |>, this gives us pretty syntax:

dependency |>
    { package, output }: package.${output}
  | { package }: package
  | package: package

Here a dependency can be a package, a wrapper around a package, or a request for a particular output.

The same branches can be used wherever a function is expected:

builtins.map (
    { file, line, ... }: "${file}:${toString line}"
  | { file, ... }: file
  | _: "<unknown>"
) locations

| would delimit function branches and bind more tightly than the pipe operators. Branches remain ordinary function values: they can be named, passed around, or assembled elsewhere.

4. Optionally, add guards and more sugar

A guard extends the applicability check. It could also express preconditions on package functions while keeping their dependency arguments visible to callPackage:

{ stdenv, ... } if stdenv.hostPlatform.isLinux: ...

Literal parameters would just be sugar for equality guards. For example, a build option selecting serial or parallel make:

makeFlags = jobs |>
    1: []
  | n if builtins.isInt n && n > 1: [ "-j${toString n}" ]
  | _: throw "jobs must be a positive integer";

Guards would participate in functionDefinedAt: a false guard means the argument does not match. Errors in the guard itself still propagate.

Optional type annotations could also desugar to the same guards. For example, a possible spelling:

(x :: Int): x + 1

could mean:

x if builtins.isInt x: x + 1
8 Likes

Sounds like good stuff, although I would caution against expanding the language too much before we have a proper langref. Do you have a prototype to play with?

1 Like

While I appreciate the motivation to make a proposal like this, I want to be a bit of a buzzkill and give some context for why this kind of proposal is unlikely to get anyways.

Nix is a very difficult language to change. It is used on a massive scale, and has no way for a file to “declare” what version it uses. Therefore, breaking changes are very difficult. It is also a very splintered language. The community primarily uses the original implementation, CppNix, but there is a significant minority that uses other implementations, such as Lix, DetNix (often called Dix). There are also several implementations in-the-work like Snix, and various vibecoded impls which I don’t expect anyone but their creators are using.

These implementations are all made without a global spec for Nix. Some of them are forks, some of them are rewrites. But they are under no mandate to match behavior with the original. Snix still doesn’t support flakes, for example, and instead aims to match behavior with Nix 2.3.

So a language change like this is

  1. Extremely breaking, as trying to evaluate a file using the operator with an older interpreter will fail to parse.
  2. Extremely splintering, as it’s likely that only some implementations will support the new operator

This situation has left the language relatively stagnant. There are numerous antifeatures in the language that developers would jump at the opportunity to remove - and Lix has done a meaningful amount of effort banning these features, and running a massive regression suite of public Nix code. But the majority of issues remain, and to preserve compatibility, exact semantics are often preserved, even when a slight change would help performance.

For an example of this phenomenon, let’s look at pipe operators. The RFC has been up for three years, and has near-universal approval. But there’s not a realistic path to merging them without breaking compat - and even if they were merged, nixpkgs would still ban their usage due to our support policy.

Language changes like this would be wonderful in theory, and I wish we did have a path to improving the language. But I don’t think it’s realistic at this time.

3 Likes

functionDefinedAt seems like it could potentially be implemented in pure Nix already (with abuse of the fact that builtins.toXML does weird things with functions):

1 Like

What support policy are you referring to?

Sticking to functionalities that are available in the nix MSV because different nix impls exist and we don’t want to break compatibility needlessly (i.e. there’s no security reason) for older systems trying to upgrade.

At the very least if a newer function is used it must have a polyfill, not sure how realistic that is with a new operator.

1 Like

@waffle8946 Are you replying to my question? If so, thanks. However, I am expecting links to written documentation. I should have been clear.

Compatibility issues arise with enviable regularity: as a rule, a few year old Nix cannot evaluate nixpkgs. Right now, this seems to be due to ./path-${x}, but there were other nuances as well (dirOf on empty string?)

2 Likes

@piegames already explored some of these ideas in a new extension of the language called nix2 in list destructuring experiment · Gerrit Code Review .

This work has not resumed due to a lack of time and a dependency on what we call langver to allow an evolution of the language seamlessly.

1 Like

Yes, it’s validated in:

and documented in the 25.11 nixpkgs release notes:

  • The minimum version of Nix required to evaluate Nixpkgs has been raised from 2.3 to 2.18.

@volth Sure, but that’s because maintaining 2.3 compat was too onerous upstream, which means 2.3 became a dead end, so the MSV had to be bumped for security reasons i.e. what I mentioned.

1 Like

Thanks for the link.

After taking a closer look at the commit introducing minfeatures.nix, its commit message and its PR discussions, I am not sure if pipe operators will be banned in Nixpkgs.

The PR author (@wolfgangwalther) says there are 4 support levels:

  1. 100% support as in: we build with this version on hydra
  2. “full” support as in: we do Eval Nixpkgs with this version regularly and commit to fixing regressions.
  3. “some” support as in: we’re not testing it via Eval, but we’re also not blocking evaluation of Nixpkgs with it in default.nix.
  4. no support as in: we’re knowingly using features that this version doesn’t support and are blocking it in default.nix.

It is likely that nix implementations of the “full support” level all support pipe operators now. If so, it is not immediately clear to me if pipe operators should be banned in Nixpkgs.

Well they don’t even work the same, see

Also they’re not stable language features yet and could easily be removed next release.

1 Like

Oh, I assume pipe operators are not experimental any more, when discussing this. Note that my first comment replied to a sentence “if they were merged, …”. Sorry if that is not clear.

The difference of pipe operators in different implementations, such as operator precedence, indeed is a good point to discuss.

2 Likes

I’d still argue the operators are kind of terrible. They’re too complicated for the casual users to use and they’re too powerless for functional programmer nerds (/a) to enjoy.

(day 352647 of praying for functional composition in nix)

I have one, but it’s not cppnix/lix/tvix. However, these days, with the help of AI, you can add an implementation for any of them in a matter of minutes.

There’s a small quirk related to the abnormal priority of the | operator (although <| and |> aren’t standard operators with numerical precedence either, so my suggestion to set the priority of | between the pipe and the rest was a bit deceitful): x: y: foo | bar should be parsed as x: ((y: foo) | bar), so it stops declaration of one lambda.