Browse Source

Add more things to `package slice`

min_max
any_of(_proc)
none_of(_proc)
all_of(_proc)
count(_proc)
gingerBill 3 years ago
parent
commit
29e660b16f
1 changed files with 96 additions and 5 deletions
  1. 96 5
      core/slice/slice.odin

+ 96 - 5
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
+}
+
+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
+}
+
 
-dot_product :: proc(a, b: $S/[]$T) -> T
+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
 }