Reputation: 26182
I have R1
and R2
record types and I need to pass either R1
or R2
to a foreign function (it can handle either r1 or r2 record structure) is it possible to do this (I thought maybe via conversion to Foreign Object)?
Or do I need to declare two different foreign imports (with different type signatures for passing R1
and R2
) pointing to the same js function?
Another way I found using unsafeCoerce
for type conversion:
foreign import data R1orR2 ∷ Type
fromR1 :: R1 -> R1orR2
fromR1 = unsafeCoerce
fromR2 :: R2 -> R1orR2
fromR2 = unsafeCoerce
So maybe there some other ways.
Upvotes: 1
Views: 54
Reputation: 80870
When writing FFI bindings, unsafeCoerce
is quite ok: after all, foreign import
has all the same drawbacks already, so you're not really losing anything.
And yes, what you came up with - R1orR2
- is the right approach that's used quite frequently in FFI bindings.
You may also want to check out undefined-is-not-a-problem
and untagged-union
libraries. They offer some more advanced and generalized techniques in this area.
Upvotes: 3