summary refs log tree commit diff
path: root/lib
diff options
context:
space:
mode:
authorRobert Hensing <robert@roberthensing.nl>2022-03-21 23:06:01 +0100
committerRobert Hensing <robert@roberthensing.nl>2022-03-21 23:14:10 +0100
commit84274cbc95b370bf8e38430453b48b7017671a8a (patch)
tree75ded95befa762cf6733c8895b50e490035ec488 /lib
parent6a0b24b27675d03a7f24c124e6c145076104e869 (diff)
downloadnixpkgs-84274cbc95b370bf8e38430453b48b7017671a8a.tar
nixpkgs-84274cbc95b370bf8e38430453b48b7017671a8a.tar.gz
nixpkgs-84274cbc95b370bf8e38430453b48b7017671a8a.tar.bz2
nixpkgs-84274cbc95b370bf8e38430453b48b7017671a8a.tar.lz
nixpkgs-84274cbc95b370bf8e38430453b48b7017671a8a.tar.xz
nixpkgs-84274cbc95b370bf8e38430453b48b7017671a8a.tar.zst
nixpkgs-84274cbc95b370bf8e38430453b48b7017671a8a.zip
lib: Add toFunction
Diffstat (limited to 'lib')
-rw-r--r--lib/default.nix3
-rw-r--r--lib/trivial.nix19
2 files changed, 21 insertions, 1 deletions
diff --git a/lib/default.nix b/lib/default.nix
index 1746efc6819..2d231bbd2d9 100644
--- a/lib/default.nix
+++ b/lib/default.nix
@@ -68,7 +68,8 @@ let
       bitNot boolToString mergeAttrs flip mapNullable inNixShell isFloat min max
       importJSON importTOML warn warnIf throwIfNot checkListOfEnum
       info showWarnings nixpkgsVersion version
-      mod compare splitByAndCompare functionArgs setFunctionArgs isFunction
+      mod compare splitByAndCompare
+      functionArgs setFunctionArgs isFunction toFunction
       toHexString toBaseDigits;
     inherit (self.fixedPoints) fix fix' converge extends composeExtensions
       composeManyExtensions makeExtensible makeExtensibleWithCustomName;
diff --git a/lib/trivial.nix b/lib/trivial.nix
index c68bac902e9..52648125059 100644
--- a/lib/trivial.nix
+++ b/lib/trivial.nix
@@ -403,6 +403,25 @@ rec {
   isFunction = f: builtins.isFunction f ||
     (f ? __functor && isFunction (f.__functor f));
 
+  /*
+    Turns any non-callable values into constant functions.
+    Returns callable values as is.
+
+    Example:
+
+      nix-repl> lib.toFunction 1 2
+      1
+
+      nix-repl> lib.toFunction (x: x + 1) 2
+      3
+  */
+  toFunction =
+    # Any value
+    v:
+    if isFunction v
+    then v
+    else k: v;
+
   /* Convert the given positive integer to a string of its hexadecimal
      representation. For example: