Return hashmap as list

Hello!

I want to return a list of store entries in a hashmap (Motoko). I’ve tried various things but keep getting type errors. I think I’m missing something simple, but can’t figure it out!

  public query func list(): async [Child] {
    return Iter.toArray(store.entries());
  };
 type error [M0096], expression of type
  Iter/1<(Text, Text)> = {next : () -> ?(Text, Text)}
cannot produce expected type
  [Child/1]
1 Like

I think we’ll need more context. What is the type of store, and what is the definition of type Child?

this is my store

  stable var entries : [(Text, Text)] = [];

  let store: HM.HashMap<Text, Text> = HM.fromIter(entries.vals(), 16, Text.equal, Text.hash);

and this is the Child type def

  public type Child = {
    name: Text;
    child_id: Text;
  };

The problem is that your call to Iter.toArray produces a [(Text, Text)], but your function is declared to return a [Child]. A Child is not a pair of Text.

FWIW, I cannot reproduce the error message you showed. I see:

cannot implicitly instantiate function of type
  <A>(Iter/7<A>) -> [A]
to argument of type
  Iter/7<(Text, Text)>
to produce result of type
  [Child/5]
because implicit instantiation of type parameter A is over-constrained with
  (Text, Text)  <:  A  <:  Child/5
where
  (Text, Text)  </:  Child/5
so that no valid instantiation exists
1 Like

Thanks, it works now