Customize variant int representation

Since variants without payloads are compiled to int, is it possible to change the number used to represent a given variant with an annotation, like @bs.as?

As far as I know, it was possible with @bs.deriving(jsConverter), but it’s not even documented anymore and it required a conversion, which is not ideal.

1 Like

Has anyone got any idea?

I wish this was something built into ocaml because I could use it for c-interop as well in a native project I am working on :grin:

You can use polyvars that get compiled to strings.

type example = [#some | #variants]
let example = #some // compiled to "some"

yes, the string use case is covered, it would be nice to have the same thing for ints!

this is a reasonable feature request, we will evaluate how complex on the implementation side

6 Likes

Actually, thinking about it, it’d be super handy for me too. I have a few modules that do this mapping, but it ain’t pretty. I’d get a really nice code-size reduction with this.

My 2c if this was implemented, it’d be nice if this also worked with types that have variants with data.

@jacobp100: Technicalc looks amazing. Did you create the UI using React-Native with ReScript?

The UI is React Native with TypeScript. I personally find TS is a better fit for React at the moment (but these things can change). But ReScript works great for everything in the core package - and it probably comes out to 50/50 split between TS code and ReScript code overall for the whole project

1 Like

what’s the generated code output? I remember that I have some paths to optimize such cases

@Hongbo Yeah, the code generated is huge for this. It looks like I might be able to make stuff a bit easier for myself if I use the deriving(jsConverter). But currently, I actually get the output, encode it as JSON, then import it -

(Edit - I can’t use bs.deriving, because I need some constructors that contain values - and it looks like that’s not supported)



Hi @jacobp100, if you shuffle the type definition of Ast_types.t a little bit, it should generate much better code, let me know if not.

type t = 
  | NS_0
  | NS_1 
  ..
1 Like