簡體   English   中英

在Haskell中導出記錄總數類型的Enum

[英]Deriving Enum for a sum type of records in Haskell

我有一個總和類型的記錄來表示所有內存表,並且將通過網絡發送它們。 我有一個二進制協議,需要首先在標頭中傳遞序數值(fromEnum),以確定數據與哪個表關聯。 問題在於求和類型需要從Enum派生,但它不想這樣做。

data Table = MarketData {bid::[Float], ask::[Float]}
     | Trade {price::[Float], qty::[Float]} 
        deriving Enum

main :: IO ()
main = do
    print $ fromEnum Trade

這是編譯錯誤

Can't make a derived instance of `Enum Table':
  `Table' must be an enumeration type
  (an enumeration consists of one or more nullary, non-GADT constructors)
In the data declaration for `Table'

我無需編寫樣板就可以做到這一點的任何想法:

ordinalVal :: Table -> Int
ordinalVal tbl = case tbl of
      MarketData{bid=_, ask=_} -> 0
    | Trade{price=_, qty=_} -> 1

如果只想枚舉構造函數,則可以使用Data.Data模塊,如下所示:

{-# LANGUAGE DeriveDataTypeable #-}
import Data.Data

data T a b = C1 a b | C2 deriving (Typeable, Data)

main = print $ constrIndex $ toConstr x
  where
    x :: T Int Int
    x = C1 1 1  -- will print 1
    -- x = C2  -- will print 2

如果您TypebaleData類型類的使用之路,也可以像您建議的那樣簡單地編寫一個Typebale Table -> Int函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM