motokointernet-computer

Motoko Immutable Array Type Definition


TL;DR - What methods/properties/functionalities are available for immutable arrays [T] (or any built in type)?


Long Version

I have been looking for basic functionality around built in types such as arrays [T] but with not a lot of luck. I can find information around base library helper methods and higher level types but not base array info I cannot find.

Looking in the docs on smartcontracts.org I can find very basic information about them. Such as:

https://smartcontracts.org/docs/language-guide/mutable-state.html#immutable-arrays https://smartcontracts.org/docs/language-guide/language-manual.html#exp-arrays

I need to find the length of arrays and what are the best ways of appending/modifying arrays. There are things in mo:base/Array, but curious to all the built in functionality, if any.

https://github.com/dfinity/motoko-base/blob/master/src/Array.mo

My only guess is the [T] is an Iter<T> = { next : () -> ?T } and that its using Iter<T>.size(). If thats the case then [T] would need a next : () -> ?T method, but I cant find where that is defined.


Solution

  • For basic functionality and types you need to take a look into motoko implementation (https://github.com/dfinity/motoko).

    If you are interested in motoko types you can find it here: https://github.com/dfinity/motoko/blob/master/src/mo_types/type.ml

    When it comes to Array's built in methods there are:

    method Immutable array Mutable Array
    size
    get
    keys
    vals
    put

    If you are interested a little bit more you can find some information here: https://github.com/dfinity/motoko/blob/master/src/mo_interpreter/interpret.ml (Section (* Overloaded dot implementations *))

    And here: https://github.com/dfinity/motoko/blob/master/src/prelude/internals.mo


    Example of script utilising some of the built in methods.

    actor ArrayLen {
      let my_array : [var Nat] = [var 1, 3];
      
      public query func my_array_size() : async Nat {
        return my_array.size();
      };
    
      public func change_last_value(n : Nat) :  async Bool {
        my_array.put(my_array.size()-1 , n);
        return true;
      };
    
      public func get_last_value() :  async Nat {
        return my_array.get(my_array.size()-1);
      };
    };
    ``