How do you construct a Belt.MutableMap?


#1

In TokenType.re I have:

type t = 
  | PLUS
  | MINUS;

type identity = t;

and in OtherFile.re I have:

let map = Belt.MutableMap.make(TokenType);

I’m getting the following error which I don’t know how to resolve:

  The variant constructor TokenType can't be found.
  
  - If it's defined in another module or file, bring it into scope by:
    - Annotating it with said module name: let food = MyModule.Apple
    - Or specifying its type: let food: MyModule.fruit = Apple
  - Constructors and modules are both capitalized. Did you want the latter?
    Then instead of let foo = Bar, try module Foo = Bar.

#2

Maybe try let map = Belt.MutableMap.make(TokenType.t);? This is the variant constructor in Token.re, isn’t it?:

type t = 
  | PLUS
  | MINUS;


#3

It seems we forget to provide a functor interface, can you log an issue on github.

let m = Belt.MutableMap.make ~id:(Belt.Id.comparable ~cmp:(fun (x : t) y  -> compare x y)) 

should work


#4

@bobzhang maybe I’m missing something, but it works?


#5

I gave this a try. I’m using Reason syntax so I wasn’t a 100% sure how to convert the syntax. I also decided to simplify the example to use int instead of TokenType. Here’s what I came up with:

let cmp = Belt.Id.comparable(~cmp=(x: int, y: int) => Pervasives.compare(x, y));
let m = Belt.MutableMap.make(~id=cmp);

The first line is okay except for the deprecation warning. The second line results in the following error:

  This has type:
    (module Belt.Id.Comparable with type t = int)
  But somewhere wanted:
    Belt.MutableMap.id('a, 'b) (defined as
      (module Belt_Id.Comparable with type identity = 'b and type t = 'a))

#6

Try it:

module TokenType = {
  type t =
    | PLUS
    | MINUS;
};

module TokenTypeComparable = {
  include
    Belt.Id.MakeComparable(
      {
        include TokenType;
        let cmp = Pervasives.compare;
      },
    );
};

let myMap = Belt.MutableMap.make(~id=(module TokenTypeComparable));

Belt.MutableMap.set(myMap, TokenType.PLUS, 1);
Belt.MutableMap.set(myMap, TokenType.PLUS, 2);
Belt.MutableMap.set(myMap, TokenType.MINUS, 3);

#7

I finally got around to trying this code out and it worked. Thank you!