I’ve been amending the ToDo and superhero examples, and ive been successfully able to call Trie.replace with a new element. However, i am now having issues trying to create a method which will find the existing element in the Trie, update that element, and then replace the element in the Trie.
I’ve tried quite a few different ways and have made changes based on the answer given How to work with type record - #4 by rbole here.
I’ve pasted the full script import List "mo:base/List";import Option "mo:base/Option";import Trie "mo:ba - Pastebin.com here.
But I think the relevant code is below:
public type MarketId = Nat32;
private stable var allMarkets : Trie.Trie<MarketId, MarketBook> = Trie.empty();
public func make_trade(tradeSide : Text, tradeMarketId : MarketId, tradeRunner : Text, tradeAmount : Nat32) : async Bool {
let orderId = nextOrderId;
nextOrderId += 1;
let complete = true;
let order : Order = { side = tradeSide; market = tradeMarketId; runner = tradeRunner; amount = tradeAmount};
var market = Trie.find(allMarkets, key(tradeMarketId), Nat32.equal);
switch (market) {
case(null) {return false};
case(?notNullMarket) {
let updatedMarket = add_trade_market(notNullMarket, order);
allMarkets := Trie.replace(
allMarkets,
key(tradeMarketId),
Nat32.equal,
?updatedMarket,
).0;
return true;
};
};
return true;
};
public func add_trade_market(aMarket : MarketBook, anOrder : Order) : async MarketBook {
var newMarket : MarketBook = {marketName = aMarket.marketName;
status = "open_for_orders";
runner1 = aMarket.runner1;
runner2 = aMarket.runner2;
orders = List.push<Order>(anOrder, aMarket.orders);
matched = aMarket.matched;
};
return newMarket;
};
If i try and compile the above script i get the following error:
stdin:74.25-79.16: type error [M0096], expression of type
Trie/42<Nat32, Any> = {
#branch : Branch/42<Nat32, Any>;
#empty;
#leaf : Leaf/42<Nat32, Any>
}
cannot produce expected type
{
#branch : Branch/42<MarketId/42, MarketBook/42>;
#empty;
#leaf : Leaf/42<MarketId/42, MarketBook/42>
}
My experience with programming has only been with duck typed languages, but i think the above error is saying that i am trying to a replace key value pair Nat32, Any with MarketId, MarketBook. Is that correct?
I’ve tried quite a few different implementations, but they have always created errors.
As stated above, i would like to create a method which will find the existing element in the Trie, update that element, and then replace the element in the Trie.
Any help or advice would be appreciated.