Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transform an array into a buffer via Array.buffer. #387

Merged
merged 4 commits into from
Jun 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/Array.mo
Original file line number Diff line number Diff line change
Expand Up @@ -296,4 +296,12 @@ module {
xs[size - 1 - n];
});
};

public func buffer<A>(xs : [A]) : Buffer.Buffer<A> {
let buff = Buffer.Buffer<A>(xs.size());
for (x in xs.vals()) {
buff.add(x)
};
buff
};
}
5 changes: 5 additions & 0 deletions test/arrayTest.mo
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,11 @@ let suite = Suite.suite("Array", [
"reverse",
Array.reverse<Nat>([0, 1, 2, 3]),
M.equals(T.array<Nat>(T.natTestable, [3, 2, 1, 0]))
),
Suite.test(
"buffer",
Array.buffer<Nat>([0, 1, 2, 3]).toArray(),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are the type parameters needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I'm not sure. I copied the code (including the type parameters) from the prior test and adapted it. Will check.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like the type arguments are indeed required:

arrayTest.mo:222.5-222.31: type error [M0098], cannot implicitly instantiate function of type
  <A>[A] -> Buffer<A>
to argument of type
  [Nat]
because implicit instantiation of type parameter A is under-constrained with
  Nat  <:  A  <:  Any
where
  Nat  =/=  Any
so that explicit type instantiation is required

https://github.com/dfinity/motoko-base/runs/6870423809?check_suite_focus=true#step:8:373

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The type instantiation is necessary because buffer is invariant (right?) so there is no principal choice.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd add a doc comment and maybe consider adding a more general 'fromIter' method too, especially if we already have 'toIter'.

M.equals(T.array<Nat>(T.natTestable, [0, 1, 2, 3]))
)
]);

Expand Down