From 0efb9825f0f09c554ffa715745e4da1d7a561c69 Mon Sep 17 00:00:00 2001 From: Veit Heller Date: Fri, 17 Sep 2021 05:58:39 +0200 Subject: [PATCH] feat: add Dynamic.List.find-index (#1316) --- core/List.carp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/core/List.carp b/core/List.carp index c6f8d2bb..43a6950e 100644 --- a/core/List.carp +++ b/core/List.carp @@ -347,11 +347,26 @@ elements is uneven, the trailing element will be discarded.") (defndynamic set-nth [l n elem] (List.update-nth l n (fn [_] elem))) - (doc find "finds the first element in the list `l` that matches `pred`.") + (doc find + "finds the first element in the list `l` that matches `pred`. + +Returns `nil` on failure") (defndynamic find [l pred] (cond (empty? l) '() (pred (car l)) (car l) (List.find (cdr l) pred))) + + (doc find-index "like [`find](#find), but returns the index instead. + +Returns `nil` on failure") + (defndynamic find-index [l pred] + (cond + (empty? l) '() + (pred (car l)) 0 + (let [res (List.find-index (cdr l) pred)] + (if (nil? res) + res + (inc res))))) ) )