Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Coerce from custom datatype to Maybe

I have:

data Time a = NoTime | Time a

and I want to convert it by rules:

NoTime -> Nothing
Time a -> Just a

Time a and Maybe a are isomorphic types (yes?), but it seems I cannot coerce Time a to Maybe a (due to "custom type error"). What is the most elegant and maybe shortest way to do it (not plain case)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Data.Coerce.coerce requires more than isomorphism. It is only capable of navigating newtype wrappers. You have two unrelated types which happen to have the same representation, and coerce can’t do anything with that.

unsafeCoerce would probably work, but it’s obviously unsafe, and I don’t think there is any guarantee that types with a similar structure must be represented the same way.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading