From 29e660b16f18df2c3d6781fef5d1baa3faac0c94 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 8 Mar 2022 10:02:40 +0000 Subject: [PATCH] Add more things to `package slice` min_max any_of(_proc) none_of(_proc) all_of(_proc) count(_proc) --- core/slice/slice.odin | 101 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 96 insertions(+), 5 deletions(-) diff --git a/core/slice/slice.odin b/core/slice/slice.odin index 5fecc76b1..520e3e1e0 100644 --- a/core/slice/slice.odin +++ b/core/slice/slice.odin @@ -304,7 +304,7 @@ filter :: proc(s: $S/[]$U, f: proc(U) -> bool, allocator := context.allocator) - return r[:] } -scanner :: proc (s: $S/[]$U, initializer: $V, f: proc(V, U)->V, allocator := context.allocator) -> []V { +scanner :: proc (s: $S/[]$U, initializer: $V, f: proc(V, U) -> V, allocator := context.allocator) -> []V { if len(s) == 0 { return {} } res := make([]V, len(s), allocator) @@ -344,15 +344,106 @@ max :: proc(s: $S/[]$T) -> (res: T, ok: bool) where intrinsics.type_is_ordered(T return } +min_max :: proc(s: $S/[]$T) -> (min, max: T, ok: bool) where intrinsics.type_is_ordered(T) { + if len(s) != 0 { + min, max = s[0], s[0] + ok = true + for v in s[1:] { + min = builtin.min(min, v) + max = builtin.max(max, v) + } + } + return +} -dot_product :: proc(a, b: $S/[]$T) -> T +any_of :: proc(s: $S/[]$T, value: T) -> bool where intrinsics.type_is_comparable(T) { + for v in s { + if v == value { + return true + } + } + return false +} + +none_of :: proc(s: $S/[]$T, value: T) -> bool where intrinsics.type_is_comparable(T) { + for v in s { + if v == value { + return false + } + } + return true +} + +all_of :: proc(s: $S/[]$T, value: T) -> bool where intrinsics.type_is_comparable(T) { + if len(s) == 0 { + return false + } + for v in s { + if v != value { + return false + } + } + return true +} + + +any_of_proc :: proc(s: $S/[]$T, f: proc(T) -> bool) -> bool { + for v in s { + if f(v) { + return true + } + } + return false +} + +none_of_proc :: proc(s: $S/[]$T, f: proc(T) -> bool) -> bool { + for v in s { + if f(v) { + return false + } + } + return true +} + +all_of_proc :: proc(s: $S/[]$T, f: proc(T) -> bool) -> bool { + if len(s) == 0 { + return false + } + for v in s { + if !f(v) { + return false + } + } + return true +} + + +count :: proc(s: $S/[]$T, value: T) -> (n: int) where intrinsics.type_is_comparable(T) { + for v in s { + if v == value { + n += 1 + } + } + return +} + +count_proc :: proc(s: $S/[]$T, f: proc(T) -> bool) -> (n: int) { + for v in s { + if f(v) { + n += 1 + } + } + return +} + + +dot_product :: proc(a, b: $S/[]$T) -> (r: T, ok: bool) where intrinsics.type_is_numeric(T) { if len(a) != len(b) { - panic("slice.dot_product: slices of unequal length") + return } - r: T #no_bounds_check for _, i in a { r += a[i] * b[i] } - return r + return r, true }