Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow customization of record field unpacking for TaggedObject #1090

Open
tysonzero opened this issue Apr 4, 2024 · 0 comments
Open

Allow customization of record field unpacking for TaggedObject #1090

tysonzero opened this issue Apr 4, 2024 · 0 comments

Comments

@tysonzero
Copy link

Currently the only way to get record field unpacking when using a sum-of-records is to avoid intermediate types and use the horrible misfeature that is partial record fields.

data Vehicle = Car { make :: String, speed :: Int } | Bicycle { brand :: String, gears :: Int }
    deriving (Generic, ToJSON)

encode $ Car { make = "MINI", speed = 150 }
> {"tag":"Car","make":"MINI","speed":150}

vs:

data Vehicle = VehicleCar Car | VehicleBicycle Bicycle
    deriving (Generic, ToJSON)

data Car = Car { make :: String, speed :: Int }
    deriving (Generic, ToJSON)

data Bicycle = Bicycle { brand :: String, gears :: Int }
    deriving (Generic, ToJSON)

encode . VehicleCar $ Car { make = "MINI", speed = 150 }
> {"tag":"VehicleCar","contents":{"speed":150,"make":"MINI"}}

If TaggedObject had an unpack :: Bool parameter users would be able to decide if they want unpacking or not, using contentsFieldName when it's False. Alternatively you could make contentsFieldName a Maybe String, this would just prevent any kind of error recovery if one of the sub-objects serializes to something other than a record, although it's unclear if such error recovery would be desirable anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant