From 94cbfe30ebd11d5310cb43ad5e8c9be226de2081 Mon Sep 17 00:00:00 2001 From: Lars Mueller Date: Fri, 30 Sep 2022 15:14:14 +0200 Subject: [PATCH] Add iterator.(reduce|any|all) --- iterator.lua | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/iterator.lua b/iterator.lua index 0ce040c..5b0642b 100644 --- a/iterator.lua +++ b/iterator.lua @@ -62,6 +62,33 @@ function iterator.aggregate(binary_func, total, ...) return total end +-- Like `iterator.aggregate`, but does not expect a `total` +function iterator.reduce(binary_func, iterator, state, control_var) + local total = iterator(state, control_var) + if total == nil then + return -- nothing if the iterator is empty + end + for value in iterator, state, total do + total = binary_func(total, value) + end + return total +end +iterator.fold = iterator.reduce + +function iterator.any(...) + for val in ... do + if val then return true end + end + return false +end + +function iterator.all(...) + for val in ... do + if not val then return false end + end + return true +end + function iterator.min(less_than_func, ...) local min for value in ... do