Home > Net >  Coerce from custom datatype to Maybe
Coerce from custom datatype to Maybe

Time:10-03

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)?

CodePudding user response:

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.

  • Related