2017-09-16 139 views
3

我有一些困難,找出爲什麼下面的代碼不起作用。我期望,因爲Command數據類型是ServerCommandClientCommand任何類型的構造函數,預計Command將能夠接受一個或另一個。我似乎對這些數據類型應該如何排隊有一個基本的誤解。Haskell類型混淆;無法匹配預期的類型,無論是/或關係

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!")) 

當我嘗試這種代碼加載到ghci中,我得到以下錯誤:

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. 

回答

8
data Command  = ServerCommand | ClientCommand 

這不會做你認爲它。如果你想,可以存儲無論是ServerCommandClientCommand,您可以使用庫類型

type Command = Either ServerCommand ClientCommand 

或創建自己的數據類型(提示:與data Bool = True | False比較,考慮的差異。)

data Command = S ServerCommand | C ClientCommand 

雖然我們在這,考慮沿

data ClientCommand = SEND String | 
        DISCONNECT | 
        CONNECT 
線路重新設計你的數據

並完全放棄了Frame

相關問題