summary refs log tree commit diff
path: root/lib/tests/misc.nix
diff options
context:
space:
mode:
authorProfpatsch <mail@profpatsch.de>2019-10-18 17:57:33 +0200
committerProfpatsch <mail@profpatsch.de>2019-10-21 13:19:16 +0200
commit8252861507ef85b45f739c63f27d4e9a80b31b31 (patch)
treefc6346d3bf0ed219cab72332d17ffb2fe857dac1 /lib/tests/misc.nix
parent360e57a567a7cb8fbe3d1f41dbb09238eccddefa (diff)
downloadnixpkgs-8252861507ef85b45f739c63f27d4e9a80b31b31.tar
nixpkgs-8252861507ef85b45f739c63f27d4e9a80b31b31.tar.gz
nixpkgs-8252861507ef85b45f739c63f27d4e9a80b31b31.tar.bz2
nixpkgs-8252861507ef85b45f739c63f27d4e9a80b31b31.tar.lz
nixpkgs-8252861507ef85b45f739c63f27d4e9a80b31b31.tar.xz
nixpkgs-8252861507ef85b45f739c63f27d4e9a80b31b31.tar.zst
nixpkgs-8252861507ef85b45f739c63f27d4e9a80b31b31.zip
lib/trivial: add `pipe` function
`pipe` is a useful operator for creating pipelines of functions.

It works around the usual problem of e.g. string operations becoming
deeply nested functions.

In principle, there are four different ways this function could be
written:

pipe val [ f1 .. fn ]
pipe val [ fn .. f1 ]
compose [ f1 .. fn ] val
compose [ fn .. f1 ] val

The third and fourth form mirror composition of functions, they would
be the same as e.g. `(f1 << f2 << f3 .. << fn) val`.
However, it is not clear which direction the list should have (as one
can see in the second form, which is the most absurd.

In order not to confuse users, we decide for the most “intuitive”
form, which mirrors the way unix pipes work (thus the name `pipe`).
The flow of data goes from left to right.

Co-Authored-By: Silvan Mosberger <infinisil@icloud.com>
Diffstat (limited to 'lib/tests/misc.nix')
-rw-r--r--lib/tests/misc.nix25
1 files changed, 25 insertions, 0 deletions
diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix
index e5d76d4e57b..b064faa1e1b 100644
--- a/lib/tests/misc.nix
+++ b/lib/tests/misc.nix
@@ -18,6 +18,31 @@ runTests {
     expected = 2;
   };
 
+  testPipe = {
+    expr = pipe 2 [
+      (x: x + 2) # 2 + 2 = 4
+      (x: x * 2) # 4 * 2 = 8
+    ];
+    expected = 8;
+  };
+
+  testPipeEmpty = {
+    expr = pipe 2 [];
+    expected = 2;
+  };
+
+  testPipeStrings = {
+    expr = pipe [ 3 4 ] [
+      (map toString)
+      (map (s: s + "\n"))
+      concatStrings
+    ];
+    expected = ''
+      3
+      4
+    '';
+  };
+
   /*
   testOr = {
     expr = or true false;