From 9ac6d45bd6d491c066121725277b5b13f6519339 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 6 Nov 2020 00:38:03 +0000 Subject: [PATCH] Add more procedures to `package slice` --- core/slice/slice.odin | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/core/slice/slice.odin b/core/slice/slice.odin index 3076fe641..d6172e27c 100644 --- a/core/slice/slice.odin +++ b/core/slice/slice.odin @@ -252,3 +252,44 @@ get_ptr :: proc(array: $T/[]$E, index: int) -> (value: ^E, ok: bool) { as_ptr :: proc(array: $T/[]$E) -> ^E { return raw_data(array); } + + +mapper :: proc(s: $S/[]$U, f: proc(U) -> $V, allocator := context.allocator) -> []V { + r := make([]V, len(s), allocator); + for v, i in s { + r[i] = f(v); + } + return r; +} + +reduce :: proc(s: $S/[]$U, initializer: $V, f: proc(V, U) -> V) -> V { + r := initializer; + for v in s { + r = f(r, v); + } + return r; +} + +filter :: proc(s: $S/[]$U, f: proc(U) -> bool, allocator := context.allocator) -> S { + r := make([dynamic]S, 0, 0, allocator); + for v in s { + if f(v) { + append(&r, v); + } + } + return r[:]; +} + + + +dot_product :: proc(a, b: $S/[]$T) -> T + where intrinsics.type_is_numeric(T) { + if len(a) != len(b) { + panic("slice.dot_product: slices of unequal length"); + } + r: T; + #no_bounds_check for _, i in a { + r += a[i] * b[i]; + } + return r; +}