From 80ccf68f55dbb70d7e5ed52ee95b3c9d1b6ce264 Mon Sep 17 00:00:00 2001 From: Jasper Ras Date: Thu, 20 Mar 2025 11:07:49 +0100 Subject: vault backup: 2025-03-20 11:07:48 --- .../Nix/Functional programming vs imperative.md | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 3 Resources/Nix/Functional programming vs imperative.md (limited to '3 Resources/Nix/Functional programming vs imperative.md') diff --git a/3 Resources/Nix/Functional programming vs imperative.md b/3 Resources/Nix/Functional programming vs imperative.md new file mode 100644 index 0000000..8c2619a --- /dev/null +++ b/3 Resources/Nix/Functional programming vs imperative.md @@ -0,0 +1,26 @@ +--- +tags: + - programming + - nix +--- +While working on a NixOS module I made a realisation on the difference between functional and imperative programming. +I was trying to configure `systemd.tmpfiles.rules` to create directories for git repositories. After looking a bit how to iterate; i tried the following: +```nix +let + paths = ["abs_paths" ...] +in +{ + map(p: systemd.tmpfiles.rules = ["d {$p} ..."];); +} +``` +This is very much originating from the imperative mindset; we loop over a list and then do stuff like setting variables and calling other functions. However in functional programming we do not! This is the correct version in functional programming: +```nix +let + paths = [ "abs_paths" ... ]; +in +{ + systemd.tmpfiles.rules = map(p: "d ${p} ..") paths; +} +``` + +Functions are pure, we can't assign stuff inside of their bodies because that would make them impure. Instead we can just return a value; in this case an array and *then* assign it. \ No newline at end of file -- cgit v1.2.3