From 2807535792e61624a80d15e5eaeab67ae8928484 Mon Sep 17 00:00:00 2001 From: Emile Clark-Boman Date: Tue, 27 Jan 2026 11:11:53 +1000 Subject: [PATCH] add firstIndexOf, firstIndexWhere, firstWhere --- nt/primitives/bootstrap/parse/sig.nix | 2 +- nt/primitives/bootstrap/std/list.nix | 20 +++++++++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/nt/primitives/bootstrap/parse/sig.nix b/nt/primitives/bootstrap/parse/sig.nix index ae89bb2..ffbfa17 100644 --- a/nt/primitives/bootstrap/parse/sig.nix +++ b/nt/primitives/bootstrap/parse/sig.nix @@ -63,7 +63,7 @@ in rec { # S = toTypeSig type |> parseTypeSig |> map trimClassPrefix; # progress = l: x: let - # index = firstIndexOf x l; + # index = firstIndexOf x null l; # in # if index == null # then [] diff --git a/nt/primitives/bootstrap/std/list.nix b/nt/primitives/bootstrap/std/list.nix index d406671..d006f13 100644 --- a/nt/primitives/bootstrap/std/list.nix +++ b/nt/primitives/bootstrap/std/list.nix @@ -1,12 +1,16 @@ {...}: let inherit (builtins) + all + elem elemAt foldl' genList length ; in rec { + contains = sub: list: all (x: elem x list) sub; + sublist = start: count: list: let len = length list; in @@ -45,14 +49,14 @@ in rec { fold' 0; # REF: pkgs.lib.lists.findFirstIndex [MODIFIED] - firstIndexOf = x: list: let + firstIndexWhere = pred: default: list: let resultIndex = foldl' ( index: el: if index < 0 then # No match yet before the current index, we need to check the element - if el == x + if pred el then # We have a match! Turn it into the actual index to prevent future iterations from modifying it -index - 1 @@ -66,6 +70,16 @@ in rec { list; in if resultIndex < 0 - then null + then default else resultIndex; + + firstIndexOf = x: firstIndexWhere (el: el == x); + + # WARNING: returns `default` in the edgecase `pred el && el == null` + firstWhere = pred: default: list: let + index = firstIndexWhere pred null list; + in + if index == null + then default + else elemAt list index; }