De-structure and coerce PolyVar constructor?


Learning lots of interesting stuff tonight.

Question, is there a way to make biz and baz a one liner, and de-structure it so we can access their values on the right hand side?

My pseudo code (what I’d like to do but don’t know how):

| #...loaded as l(p)   => someFunc((l :> string), (p :> payload))

Here is a bigger picture from some code I found earlier and added the biz next to the baz

Original writer of code:

why not just:

  | #baz(payload)
  | #biz(payload) =>

The generated JS is quite impressively optimized by the compiler btw.

1 Like

So, I’d like to have access to the #biz, #baz part, because I’m using them as keys to call another function and cache the return values…

well you can definitely do this while keeping the pattern matching flat, eg:

 | #baz({baz}) => f1(baz)
 | #biz({biz}) => f2(biz)

I was able to achieve half of what I was searching for below, would still be great if I could de-structure the polyvar and use it to do a lookup on a Js.Dict like I did with defaultViewStyle below.

I think somehow mapping polyvars to maps or dicts somehow makes sense to me… but maybe that’s just not a great pattern?

 switch (item: cssStyle) {
      | #...defaultViewStyle as p => {
          let keyAsString = ((p :> defaultViewStyle) :> string)
          let maybeStyle = Js.Dict.get(DefaultStyleSheet.asDict, keyAsString)
          switch maybeStyle {
          | Some(cssStyle) => cssStyle
          | None => {
              Js.log(`No style found for ${keyAsString}`)
      | #...styleWithStringArg as s => getCustomStringStyle(s)
      | #...styleWithFloatArg as s => getCustomFloatStyle(s)

If you use polyvars for map/dict keys, it means you know at compile time the values of those keys so you’d rather make it a record!

1 Like

Great point, I actually might change my design a little, because maybe it makes more sense to use strings.