我是Motoko和互联网计算机的新手,当我工作时,我有太多的困难,可能看起来很简单,我很难做到这一点,在这里张贴论坛问题的链接
https://forum.dfinity.org/t/how-to-traverse-inner-array-of-a-trie/12941?u=manubodhi
如果有人精通Motoko和definition,请帮助
我在motoko playground中为您准备了一个小代码,以便了解如何遍历内部数组并实现过滤Trie的目标。这里也是保存项目在motoko游乐场:https://m7sm4-2iaaa-aaaab-qabra-cai.raw.ic0.app/?tag=1150943578
要过滤内部数组,可以使用:
let trieOfDishes = Trie.filter<DishId, Dish>(dishes, func (k, v) {
Array.find<MealTypeId>(v.mealTypeId, func(x : MealTypeId) { x == mealTypeId }) != null ;
});
容器实现的完整代码:
import Trie "mo:base/Trie";
import Array "mo:base/Array";
import Iter "mo:base/Iter";
import Nat32 "mo:base/Nat32";
actor Dishes {
type DishId = Nat32;
type DishTypeId = Nat32;
type MealTypeId = Nat32;
public type Dish = {
dishId: DishId;
dishTypeId : DishTypeId;
mealTypeId : [MealTypeId]
};
var dishes: Trie.Trie<DishId, Dish> = Trie.empty();
private func key(x : DishId) : Trie.Key<DishId> {
return { hash = x; key = x };
};
public func add_dish(dish: Dish) : async Dish {
dishes := Trie.replace(dishes, key(dish.dishId), Nat32.equal, ?dish).0;
return dish;
};
public query func getDishesByDishId (dishTypeId : DishTypeId) : async [(DishId, Dish)] {
let trieOfDishes = Trie.filter<DishId, Dish>(dishes, func (k, v) { v.dishId == dishTypeId } );
let arrayOfDishes : [(DishId, Dish)] = Iter.toArray(Trie.iter(trieOfDishes));
return arrayOfDishes;
};
public query func getDishesBymealTypeId (mealTypeId : MealTypeId) : async [(DishId, Dish)] {
let trieOfDishes = Trie.filter<DishId, Dish>(dishes, func (k, v) {
Array.find<MealTypeId>(v.mealTypeId, func(x : MealTypeId) { x == mealTypeId }) != null ;
});
let arrayOfDishes : [(DishId, Dish)] = Iter.toArray(Trie.iter(trieOfDishes));
return arrayOfDishes;
};
}