Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell type confusion; Couldn't match the expected type despite either/or relationship

I'm having some trouble figuring out why the below code isn't working. I would expect that since the Command data type is either a ServerCommand or a ClientCommand that any type constructor that is expecting a Command would be able to accept one or the other. I seem to have a fundamental misunderstanding of how these datatypes should be lining up.

data ClientCommand  =   SEND |
                        DISCONNECT |
                        CONNECT

data ServerCommand  =   CONNECTED |
                        MESSAGE |
                        RECEIPT |
                        ERROR

data Command        =   ServerCommand | ClientCommand

type Frame          =   (Command, Maybe String)

makeConnect :: Frame
makeConnect = (CONNECT, (Just "hello!"))

When I try to load this code into ghci, I get the following error:

GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Main             ( Frames.hs, interpreted )

Frames.hs:15:16:

    Couldn't match expected type ‘Command’
                with actual type ‘ClientCommand’
    In the expression: CONNECT
    In the expression: (CONNECT, (Just "hello!"))
Failed, modules loaded: none.
like image 768
wickstopher Avatar asked Dec 18 '25 20:12

wickstopher


1 Answers

data Command        =   ServerCommand | ClientCommand

This doesn't do what you think it does. (Hint: compare with data Bool = True | False, contemplate the difference.)

If you want a data type that can store either a ServerCommand or a ClientCommand, you can use a library type

type Command = Either ServerCommand ClientCommand

or create your own

data Command = S ServerCommand | C ClientCommand

While we're at it, consider redesigning your data along the lines of

data ClientCommand = SEND String |
                     DISCONNECT |
                     CONNECT

and dropping the Frame thing altogether.

like image 179
n. 1.8e9-where's-my-share m. Avatar answered Dec 21 '25 19:12

n. 1.8e9-where's-my-share m.