RNG and Cosine in Nix

https://news.ycombinator.com/rss Hits: 4
Summary

NixOS is an immutable, atomic Linux distribution with a declarative and reproducible configuration and packaging system using the purely functional, lazily evaluated, dynamically typed Nix programming language.Kublai: AAAAAAHHH too many buzzwords, what does that all mean???Glad you asked! Basically, in NixOS, you can configure your entire system using a configuration.nix file and NixOS will magically (using a bunch of Bash scripts) figure out what needs to be installed and how to do it. For instance, if you want to enable Firefox, you’d add programs.firefox.enable = true; to your configuration.nix. Easy as that.Kublai: Sure that sounds cool, but what if I want to enable Firefox with only 50% probability?Great question! The easiest solution would be something like randomNumber = 4 (from this xkcd), but what about doing the RNG using the Nix language so that it’s declarative?RNGSadly, Nix doesn’t have built-in RNG since it’s purely functional, but I found a project called rand-nix with this code:let pkgs = import <nixpkgs> { }; seed = builtins.replaceStrings [ "-" "\n" ] [ "" "" ] (builtins.readFile /proc/sys/kernel/random/uuid); hash = builtins.hashString "sha256"; rng = seed: pkgs.lib.fix (self: { int = (builtins.fromTOML "x=0x${builtins.substring 28 8 (hash seed)}").x; intBetween = x: y: x + pkgs.lib.mod self.int (y - x); next = rng (hash seed); skip = pkgs.lib.flip pkgs.lib.pipe [ (pkgs.lib.flip pkgs.lib.replicate (x: x.next)) (pkgs.lib.pipe self) ]; take = builtins.genList self.skip; }); in { a = (rng seed).int; b = builtins.readFile /proc/sys/kernel/random/uuid; } Kublai: Whoa, that’s a lot of code! What does it do?Basically, it reads random data from /proc/sys/kernel/random/uuid, SHA256es it, and parses the hex string using builtins.fromTOML and does a bunch of other things that you don’t need to worry about. Anyways, let’s run it with nix eval --file main.nix and see what it prints out:{ a = 3106154414; b = ""; } SHL: This post uses some experimental Nix featu...

First seen: 2025-04-15 16:12

Last seen: 2025-04-15 19:14