Nicolas Henin
Nicolas Henin

Reputation: 3334

Pattern Matching fields but also have a variable that represents the entire datatype

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

Answers (1)

Nicolas Henin
Nicolas Henin

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

Related Questions