diff --git a/lib/std/core/array.c3 b/lib/std/core/array.c3 index 12fd61ab6..440c01700 100644 --- a/lib/std/core/array.c3 +++ b/lib/std/core/array.c3 @@ -2,6 +2,25 @@ module std::core::array; import std::core::array::slice; <* + Returns true if the array contains at least one element, else false + + @param [in] array + @param [in] element + @require @typekind(array) == SLICE || @typekind(array) == ARRAY + @require @typeis(array[0], $typeof(element)) : "array and element must have the same type" +*> +macro bool contains(array, element) +{ + foreach (&item : array) + { + if (*item == element) return true; + } + return false; +} + +<* + Return the first index of element found in the array, searching from the start. + @param [in] array @param [in] element @return "the first index of the element" @@ -39,6 +58,8 @@ macro slice2d(array_ptr, x = 0, xlen = 0, y = 0, ylen = 0) <* + Return the first index of element found in the array, searching in reverse from the end. + @param [in] array @param [in] element @return "the last index of the element" diff --git a/releasenotes.md b/releasenotes.md index 6e73d7124..ce86d3dc9 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -33,6 +33,7 @@ ### Stdlib changes - Hash functions for integer vectors and arrays. - Prefer `math::I` and `math::I_F` for `math::IMAGINARY` and `math::IMAGINARYF` the latter is deprecated. +- Add `array::contains` to check for a value in an array or slice. ## 0.7.0 Change list diff --git a/test/unit/stdlib/core/array.c3 b/test/unit/stdlib/core/array.c3 index 75cf37053..f05beb051 100644 --- a/test/unit/stdlib/core/array.c3 +++ b/test/unit/stdlib/core/array.c3 @@ -1,5 +1,12 @@ module arraytests @test; +fn void contains() +{ + int[3] a = { 1, 2, 3 }; + assert(array::contains(a, 2) == true); + assert(array::contains(a, 15) == false); +} + fn void find() { int[3] a = { 1, 2, 3 };