Nix Language Quirks: Difference between revisions

Add example of using fromTOML for parsing hex/octal/binary number formats
Add case statement example
Line 216: Line 216:
9
9
</syntaxHighlight>
</syntaxHighlight>
== Mimicking case statements with attribute sets ==
Nix doesn't include native support for case statements, however when dealing with string types it's possible to use some string interpolation behavior to achieve something similar to case statement behavior, as described in this [https://discourse.nixos.org/t/case-statement-expr/27741/12 thread].
In the example from the thread, given some string argument <code>x</code>, the following code would place different values into a text file depending on it's value:
<syntaxHighlight lang=nix>
environment.etc."just/for/test".text = {
  "a" = "hello";
  "b" = "hi";
  "c" = "ciao";
}." ${x}";
</syntaxHighlight>
So if <code>x</code> is set to the string <code>"a"</code> then the <code>just/for/test</code> file contents would be set to the string <code>"hello"</code>. The code above is the same in behavior to the following, more common, if-else-style construct:
<syntaxHighlight lang=nix>
environment.etc."just/for/test".text =
  if x == "a" then
    "hello"
  else if x == "b" then
    "hi"
  else if x == "c" then
    "ciao"
  else
    abort "x is invalid";
</syntaxHighlight>
There is an example in <code>coq</code> package code [https://github.com/NixOS/nixpkgs/blob/5185539c51ba658e70b29e01c0c320a85f4e2098/pkgs/build-support/coq/extra-lib.nix#L98 here] where someone used this behavior to build a reusable function <code>switch</code>.


== Nix Language FAQ ==
== Nix Language FAQ ==