diff --git a/docs/docs/noir/concepts/data_types/arrays.md b/docs/docs/noir/concepts/data_types/arrays.md index bb68e60fe53..289145a8c4d 100644 --- a/docs/docs/noir/concepts/data_types/arrays.md +++ b/docs/docs/noir/concepts/data_types/arrays.md @@ -203,6 +203,8 @@ fn main() { Same as fold, but uses the first element as the starting element. +Requires `self` to be non-empty. + ```rust fn reduce(self, f: fn(T, T) -> T) -> T ``` diff --git a/noir_stdlib/src/array/mod.nr b/noir_stdlib/src/array/mod.nr index 46acf619dd2..f5089de1877 100644 --- a/noir_stdlib/src/array/mod.nr +++ b/noir_stdlib/src/array/mod.nr @@ -43,10 +43,10 @@ impl [T; N] { /// assert_eq(b, [2, 4, 6]); /// ``` pub fn map(self, f: fn[Env](T) -> U) -> [U; N] { - let first_elem = f(self[0]); - let mut ret = [first_elem; N]; + let uninitialized = crate::mem::zeroed(); + let mut ret = [uninitialized; N]; - for i in 1..self.len() { + for i in 0..self.len() { ret[i] = f(self[i]); } @@ -79,6 +79,8 @@ impl [T; N] { } /// Same as fold, but uses the first element as the starting element. + /// + /// Requires the input array to be non-empty. /// /// Example: /// @@ -217,3 +219,10 @@ impl From> for [u8; N] { s.as_bytes() } } + +mod test { + #[test] + fn map_empty() { + assert_eq([].map(|x| x + 1), []); + } +}