If you have been struggling with Motoko Arrays and the examples provided in the documentation, you are not alone! I tried the following example from the documentation:
let array1 : [Nat] = [1, 2, 3, 4, 6, 7, 8] ;
let array2 : [Nat] = Array_tabulate<Nat>(7, func(i:Nat) : Nat {
if ( i == 2 or i == 5 ) { array1[i] * i } // change 3rd and 6th entries
else { array1[i] } // no change to other entries
}) ;
Calling the Array _tabulate
function didnt’t work for me, even though it was stated that it’s in the compiler Prelude and doesn’t need additional imports.
What you need to do instead is the following:
import Array "mo:stdlib/array.mo";
let array1 : [Nat] = [1, 2, 3, 4, 6, 7, 8] ;
let array2 : [Nat] = Array.tabulate<Nat>(7, func(i:Nat) : Nat {
if ( i == 2 or i == 5 ) { array1[i] * i } // change 3rd and 6th entries
else { array1[i] } // no change to other entries
}) ;
The same goes for Array_init
which you would call the following way:
import Array "mo:stdlib/array.mo";
let x : [var Bool] = Array.init<Bool>(5,false);
This gives you an array the size of 5 holding the initial value false
for each entry.
Looking at programs implemented by the team is a big help, i can only recommend to check out Linkedup and @enzo 's GitHub together with Sample Code from the documentation.