m-bock/purescript-ts-bridge

Variant encodings and typescript side pattern matching

Closed this issue · 1 comments

Hi there,

I'm wondering if you use a particular approach to pattern matching on the typescript side? AFAIA there are a number of ways to do so and I'd like to pick one which has a good chance of being maintained:

Do you recommend any approach which would enable compositional pattern matching like in purescript-variant, like https://paarthenon.github.io/variant/docs/intro#grouping ?

Cheers,

Jun

m-bock commented

Generally I'd say the way how pattern matching is done on the typescript side is not so important for this library. The encoding matters though. And via variant-encodings I wanted to provide the most common encodings. If you use a library that uses a different encoding and it's common it can be added to variant-encodings lib and bindings here.

Depending on what you're doing, another option is to just export an ADT as opaque type and then provide constructors and destructors, something like:

data Foo = A Int | B String

mkFoo :: {
  _A :: Int -> Foo,
  _B :: String -> Foo
}
mkFoo = ...

matchFoo :: { onA :: Int -> z, onB :: String -> z } -> Foo -> z
matchFoo = ...

With the implementations written manually (for now) and maybe with a generic function in the future. Those functions you can export with ts-bridge right away.

Regarding the compositional matching, that's an interesting point I did not think about yet. For instance we cannot just generate types for variant's onMatch because of the type class constraints. But you can write a TS function that does the same, however expressing the type level code with TS type level code. But this is all on the TS side. And this should work for every kind of encoding.