Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

purescript - Pass polymorphic record to foreign function

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.

question from:https://stackoverflow.com/questions/65837499/pass-polymorphic-record-to-foreign-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...