Przeglądaj źródła

Add more procedures to `package slice`

gingerBill 4 lat temu
rodzic
commit
9ac6d45bd6
1 zmienionych plików z 41 dodań i 0 usunięć
  1. 41 0
      core/slice/slice.odin

+ 41 - 0
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;
+}