Reduce a buffer to variant in Motoko

I try to convert an array, a buffer, to a variant tree. In JavaScript I would .reduce() it but I cannot wrap my head around how I should solve that in Motoko.

Anyone has maybe an example to share that show how to reduce a Buffer?

// The types
module {
    public type Hash = Blob;
    public type Key = Blob;
    public type Value = Blob;
    
    public type HashTree = {
        #empty;
        #pruned : Hash;
        #fork : (HashTree, HashTree);
        #labeled : (Key, HashTree);
        #leaf : Value;
    };
};

// What I am trying to do
public query func say() : async HashTree {
    let tmp = Buffer.Buffer<(HashKey, HashTree)>(1);
    tmp.add((Text.encodeUtf8("a"), #empty));
    tmp.add((Text.encodeUtf8("b"), #empty));

    let labeled = Buffer.Buffer<HashTree>(1);

    for (val in tmp.vals()) {
      labeled.add(#labeled val);
    };

    // What I try to achieve dynamically
    let goal = #labeled(
      "http_assets",
      #fork(
        #fork(
          #labeled ("/a",
            #leaf (Text.encodeUtf8("a"))
          ),
          #labeled ("/b",
            #leaf (Text.encodeUtf8("b"))
          )
        ),
        #fork(
          #labeled ("/c",
            #leaf (Text.encodeUtf8("c"))
          ),
          #empty
        )
      )
    );

    return #labeled(
        "http_assets",
        labeled.vals(), // <-- here I get lost!??!
    );
  };

Motoko playground: Motoko Playground - DFINITY

Reduce is a left fold: motoko-base/Array.mo at 08507fc9dc425144242434b8fa762c3287077335 · dfinity/motoko-base · GitHub

Here’s an example of using it:

Sorry I can’t be more helpful right now. It’s late here.

1 Like

Thanks for the quick answer, I think it answered my question or at least unblocked me!

I think but I am doing something wrong somewhere else or not fully get the tree I have to build, therefore did not went that far. Will update the thread whenever I get it.

Above answer resolve my initial question (thanks for the hint).

Ultimately I give up hacking around above hashtree and will give a shout to the nice merkle tree repo of @nomeata