Recursion in Nix language - did the language change or am I mistyping the factorial example?

Hi Nix Discourse Help,

I am reading this tutorial from 2014 about the Nix language:

I add the following to a file myfactorial.nix

  # factorial : int -> int
  factorial = n: if n == 0 then 1
                           else n * factorial (n-1);
  factorial 9

and evaluate with:

nix-instantiate --eval myfactorial.nix

and get back:

error: undefined variable 'n-1'

       at /home/i97henka/github/

            3|   factorial = n: if n == 0 then 1
            4|                            else n * factorial (n-1);
             |                                                ^
            5| in

I have tried to double check my work to make sure that I didn’t accidentally mistype anything.
Please let me know what gives.

$ nix --version
nix (Nix) 2.11.1

I guess you meant n - 1. Identifiers can have dashes in it, so n-1 is (mis)interpreted as identifier here.


Thank you, that solved my problem :pray:. The example was slightly misformatted in that case.

Another blog bug squashed. However its very hard to update blog posts and such to reflect fixes. Not everything is tracked and deployed by git :-(((((

There is no way around this problem.

1 Like

I guess it was just a typo (or just muscle memory, I mean in almost every other language n-1 is a subtraction).

When I copy the strings from the blogpost I get (n — 1), so everything seems fine. I mean, if the Nix language would suddenly change its behavior in such a drastic way that would be very bad :wink: