Reputation: 3334
I would like to pattern match on a function with the following sum type :
data CommandRequest = CreateWorkspace {commandId :: UUID , workspaceId ::UUID }
| IntroduceIdea {commandId :: UUID , workspaceId ::UUID , ideaContent :: String}
So I know how to bind variables on the fields :
instance ToJSON CommandRequest where
toJSON (CreateWorkspace commandId workspaceId) = object [
"commandId" .= commandId,
"workspaceId" .= workspaceId,
"commandName" .= pack "createWorkspace"]
toJSON (IntroduceIdea commandId workspaceId ideaContent) = object [
"commandId" .= commandId,
"workspaceId" .= workspaceId,
"commandName" .= pack "introduceIdea",
"ideaContent" .= ideaContent
]
I would like to bind the entire data type at the same time like we can do in scala :
toJSON ( myDataType @ CreateWorkspace commandId workspaceId) = ...
Do you know how to do it in haskell ?
Upvotes: 0
Views: 35
Reputation: 3334
It was an issue with parentheses !
instance ToJSON CommandRequest where
toJSON (command @ (CreateWorkspace commandId workspaceId)) = object [
"commandId" .= commandId,
"workspaceId" .= workspaceId,
"commandName" .= pack "createWorkspace"]
toJSON (command @ (IntroduceIdea commandId workspaceId ideaContent)) = object [
"commandId" .= commandId,
"workspaceId" .= workspaceId,
"commandName" .= getCommandName command,
"ideaContent" .= ideaContent
]
Upvotes: 1