Why is the List.push() method not working in this example?

I tried changing things around but the push isn’t working. Any help would be appreciated.

https://m7sm4-2iaaa-aaaab-qabra-cai.raw.ic0.app/?tag=3563088652

Here’s the code incase the playground link gets wiped:

import List "mo:base/List";

actor {
  stable let listOfNumbers = List.nil<Nat>();

  public query func getListSize(): async Nat {
    return List.size(listOfNumbers);
  };

  public func addToList(n: Nat): async () {
    ignore List.push(n, listOfNumbers);
  };
}
1 Like

This is because List.push returns a new list with n pushed to listOfNumbers. It does not change listOfNumbers itself. So you would want the following:

// `var` instead of `let`, so you can re-assign it.
stable var listOfNumbers = List.nil<Nat>();

// ...

// Update `listOfNumber` to the new list with `n` added to it.
listOfNumbers := List.push(n, listOfNumbers);

Any idea if this has the same kind of drawback that Array.append has as documented here

It should not have, since it is not reconstructing anything afaik, just pre-pending.

1 Like