Skip to content

Commit

Permalink
fix: Allow array map on empty arrays (#6305)
Browse files Browse the repository at this point in the history
# Description

## Problem\*

Resolves a private issue sent to me on slack

## Summary\*

Array map is a fairly old method written before we had
`std::mem::zeroed`. Now that we have zeroed, we can allow mapping empty
arrays since we can use `zeroed` to get the filler `U` value for the
starting elements.

## Additional Context

While I was at it I included a small clarification to `reduce`'s docs
that it requires a non-empty array

## Documentation\*

Check one:
- [ ] No documentation needed.
- [x] Documentation included in this PR.
- [ ] **[For Experimental Features]** Documentation to be submitted in a
separate PR.

# PR Checklist\*

- [x] I have tested the changes locally.
- [x] I have formatted the changes with [Prettier](https://prettier.io/)
and/or `cargo fmt` on default settings.
  • Loading branch information
jfecher authored Oct 21, 2024
1 parent 33a1e7d commit 51ae1b3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
2 changes: 2 additions & 0 deletions docs/docs/noir/concepts/data_types/arrays.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
Expand Down
15 changes: 12 additions & 3 deletions noir_stdlib/src/array/mod.nr
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ impl<T, let N: u32> [T; N] {
/// assert_eq(b, [2, 4, 6]);
/// ```
pub fn map<U, Env>(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]);
}

Expand Down Expand Up @@ -79,6 +79,8 @@ impl<T, let N: u32> [T; N] {
}

/// Same as fold, but uses the first element as the starting element.
///
/// Requires the input array to be non-empty.
///
/// Example:
///
Expand Down Expand Up @@ -217,3 +219,10 @@ impl<let N: u32> From<str<N>> for [u8; N] {
s.as_bytes()
}
}

mod test {
#[test]
fn map_empty() {
assert_eq([].map(|x| x + 1), []);
}
}

0 comments on commit 51ae1b3

Please sign in to comment.