dfinity / ic-repl

Apache License 2.0
70 stars 10 forks source link

assert vec length (size) #41

Closed AndyGura closed 2 years ago

AndyGura commented 2 years ago

Is there a way to assert vector length, e.g.

let result = call canister.getItems();
assert size(result) == (1 : nat);

Thanks!

chenyan2002 commented 2 years ago

No. But we can add a size built-in function.

AndyGura commented 2 years ago

@chenyan2002 Nice to hear! Can you please add this? Also I think length is a bit more descriptive name, to not confuse size with memory size in bytes. Looking forward for this.Thanks in advance!

AndyGura commented 2 years ago

Hey @chenyan2002 ! Thank you for looking into it. Can you please document somewhere how can I use it? I checked out both merged PR-s and unfortunately it's not clear to me how to do it

chenyan2002 commented 2 years ago

You can see a full example from: https://github.com/chenyan2002/ic-repl/blob/master/examples/func.sh.

For your specific use case,

let result = call canister.getItems();
function count(acc, x) { let _ = add(acc, 1) };
assert result.fold(0, count) == 1;

Or you can define a length function:

function count(acc, x) { let _ = add(acc, 1) };
function length(v) { let _ = v.fold(0, count) };
assert length(vec) == 1;