Polymorphism in Rescript

Hi Team,

I am trying to convert Haskell code to Rescript code. The biggest issue is Haskell has polymorphism (typeclass and instances) while Rescript doesn’t have it. How can I achieve Polymorphism in Rescript? Function overloading especially…

Thanks

I believe module functor is what you are looking for.

1 Like

Can you give an example of what you want to do?

Do you mean function overloading like if called with string do x and if called with int do y?

I think the approach to have ad-hoc typeclass-like polymorphism in ReScript would be using a first class module as a parameter to a function, like this:

But I don’t think this is encouraged by the community/core team, and it’s more of a leftover from OCaml. :thinking:

1 Like

That looks like a good use case for a variant type.

That makes a lot of sense for small, local types and is how I’d do it in this case as well, but I think what they want here is being able to define “”“instances”“” outside of the type constructor, and the module type would act like an interface from OO languages, or a typeclass from Haskell.

Variant types are a direct correspondent of sum types from Haskell, so I assume if they’re using a typeclass, it’s because they want this kind of “exterior” implementation.