summary refs log tree commit diff
path: root/lib/lists.nix
diff options
context:
space:
mode:
authorSilvan Mosberger <silvan.mosberger@tweag.io>2023-07-19 16:44:11 +0200
committerSilvan Mosberger <silvan.mosberger@tweag.io>2023-07-19 17:35:28 +0200
commit53dcfd24ad71bb1a26c9d17cbd2af1f83a2da7a3 (patch)
tree0b1bf8d1b2c9ec8163409aa4b4c9f569e877a8b8 /lib/lists.nix
parenta4f7840e1813bc389995083fac2b3bcd0ca6823d (diff)
downloadnixpkgs-53dcfd24ad71bb1a26c9d17cbd2af1f83a2da7a3.tar
nixpkgs-53dcfd24ad71bb1a26c9d17cbd2af1f83a2da7a3.tar.gz
nixpkgs-53dcfd24ad71bb1a26c9d17cbd2af1f83a2da7a3.tar.bz2
nixpkgs-53dcfd24ad71bb1a26c9d17cbd2af1f83a2da7a3.tar.lz
nixpkgs-53dcfd24ad71bb1a26c9d17cbd2af1f83a2da7a3.tar.xz
nixpkgs-53dcfd24ad71bb1a26c9d17cbd2af1f83a2da7a3.tar.zst
nixpkgs-53dcfd24ad71bb1a26c9d17cbd2af1f83a2da7a3.zip
lib.lists.findFirstIndex: init
Co-authored-by: Robert Hensing <roberth@users.noreply.github.com>
Diffstat (limited to 'lib/lists.nix')
-rw-r--r--lib/lists.nix42
1 files changed, 34 insertions, 8 deletions
diff --git a/lib/lists.nix b/lib/lists.nix
index 5d9af0cf711..c3e889644b3 100644
--- a/lib/lists.nix
+++ b/lib/lists.nix
@@ -180,18 +180,18 @@ rec {
       else if len != 1 then multiple
       else head found;
 
-  /* Find the first element in the list matching the specified
+  /* Find the first index in the list matching the specified
      predicate or return `default` if no such element exists.
 
-     Type: findFirst :: (a -> bool) -> a -> [a] -> a
+     Type: findFirstIndex :: (a -> Bool) -> b -> [a] -> (Int | b)
 
      Example:
-       findFirst (x: x > 3) 7 [ 1 6 4 ]
-       => 6
-       findFirst (x: x > 9) 7 [ 1 6 4 ]
-       => 7
+       findFirstIndex (x: x > 3) null [ 0 6 4 ]
+       => 1
+       findFirstIndex (x: x > 9) null [ 0 6 4 ]
+       => null
   */
-  findFirst =
+  findFirstIndex =
     # Predicate
     pred:
     # Default value to return
@@ -229,7 +229,33 @@ rec {
     if resultIndex < 0 then
       default
     else
-      elemAt list resultIndex;
+      resultIndex;
+
+  /* Find the first element in the list matching the specified
+     predicate or return `default` if no such element exists.
+
+     Type: findFirst :: (a -> bool) -> a -> [a] -> a
+
+     Example:
+       findFirst (x: x > 3) 7 [ 1 6 4 ]
+       => 6
+       findFirst (x: x > 9) 7 [ 1 6 4 ]
+       => 7
+  */
+  findFirst =
+    # Predicate
+    pred:
+    # Default value to return
+    default:
+    # Input list
+    list:
+    let
+      index = findFirstIndex pred null list;
+    in
+    if index == null then
+      default
+    else
+      elemAt list index;
 
   /* Return true if function `pred` returns true for at least one
      element of `list`.