fn.meetsConDo: improve performance and add documentation.

This commit is contained in:
Kevin Baensch 2024-11-30 21:10:07 +01:00
parent c1c5ff299e
commit 1812effbd7
Signed by: derped
GPG key ID: C0F1D326C7626543

39
fn.nix
View file

@ -65,17 +65,44 @@ rec {
# Not sure how list operations are implemented in Nix # Not sure how list operations are implemented in Nix
# This might be a tad bit inefficient. # This might be a tad bit inefficient.
# TODO: look for better implementation (map is a builtin function so checking that probably won't help)
# Sequentially checks elements of list (l) for condition (cond) and executes do on first match. # Sequentially checks elements of list (l) for condition (cond) and executes do on first match.
/**
Run lambda "(do element)" on the first element of list "l" where (cond element) returns true otherwise return false.
# Type
```
meetsConDo :: (any -> bool) -> (any -> any) -> [any] -> any
```
# Arguments:
- [cond] Condition function
- [do] Function to run on element if cond returns true
- [list] List of elements
# Example:
```nix
meetsConDo (element: element >= 5) (element: element + 1) [ 4 2 0 5 1 ]
=> 6
meetsConDo (element: element >= 5) (element: element + 1) [ 4 2 0 1 ]
=> false
```
*/
meetsConDo = meetsConDo =
cond: do: l: cond: do: list:
ifelse (l == [ ]) false (
let let
h = head l; listLen = length list;
t = tail l; meetsConDo' =
currentIndex:
ifelse (currentIndex == listLen) false (
let
head = elemAt list currentIndex;
in in
ifelse (cond h) (do h) (meetsConDo cond do t) ifelse (cond head) (do head) (meetsConDo' (currentIndex + 1))
); );
in
meetsConDo' 0;
deps = deps =
p: p:
ifelse (isAttrs p) (filter isAttrs ( ifelse (isAttrs p) (filter isAttrs (