diff options
Diffstat (limited to 'lib/lists.nix')
-rw-r--r-- | lib/lists.nix | 42 |
1 files changed, 34 insertions, 8 deletions
diff --git a/lib/lists.nix b/lib/lists.nix index 5d9af0cf7114e..c3e889644b3ed 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`. |