Type error [M0072] field find does not exist in type [Token]

Hello!

I want to call find() on an Array that is stored as a value in a HashMap, but I get a type error.
Why can’t I call find?

[Error]
Stderr:
type error [M0072], field find does not exist in type [Token]

[Code]

import Array "mo:base/Array";
import Buffer "mo:base/Buffer";
import HashMap "mo:base/HashMap";
import Principal "mo:base/Principal";

import T "types"; // public type Token = Principal;

module {
  public class Faucet() {

    private let TOTAL_FAUCET_AMOUNT : Nat = 100_000;
    private let FAUCET_AMOUNT : Nat = 1_000;
    private var amount_counter : Nat = 0;

    var faucet_book = HashMap.HashMap<Principal, [T.Token]>(
      0,
      Principal.equal,
      Principal.hash,
    );

    public func checkDistribution(user : Principal, token : T.Token) : T.FaucetReceipt {
      if (amount_counter >= TOTAL_FAUCET_AMOUNT) {
        return (#Err(#InsufficientToken));
      };

      switch (faucet_book.get(user)) {
        case null {
          return #Ok(FAUCET_AMOUNT);
        };
        case (?tokens) {
          switch (tokens.find(token)) { // Error
            case null {
              return #Ok(FAUCET_AMOUNT);
            };
            case (?token) return #Err(#AlreadyGiven);
          };
        };
      };
    };

    public func addUser(user : Principal, token : T.Token) {
      amount_counter += FAUCET_AMOUNT;

      switch (faucet_book.get(user)) {
        case null {
          let new_data = Array.make<T.Token>(token);
          faucet_book.put(user, new_data);
        };
        case (?tokens) {
          let buff = Buffer.Buffer<T.Token>(2);
          for (token in tokens.vals()) {
            buff.add(token);
          };
          faucet_book.put(user, buff.toArray());
        };
      };
    };
  };
};

Thank you in advance for your response.

Here’s the reference for find: Array | Internet Computer Home

As you can see it takes an array and a function as arguments. From that you can deduct that you have to call it with Array.find(tokens, <some func>), and not as a member function of the tokens array itself.

Also, the second argument is not an element, but a function that takes an element and returns a bool.

Thanks for the answer!

I checked the internal implementation of Docs and Array.find and changed it as follows, but I get the same error.

Is there something wrong with the way I specify it?

It’s supposed to be Array.find(tokens, <func>), not tokens.find(tokens, <func>)

This is because find is a member of the Array module, not a member function of the array object

1 Like