我有一个 Haskell 项目,它使用了一些newtypes. 我想导出这些表格,因此我可以将它包含在我的文档(非黑线鳕)中,例如作为降价表。我对此并不熟悉,但通过阅读,我的计划是使用Generics/Data.Data, 创建一些大致如下所示的函数:
data MyRowRepresentation = MyRowRepresentation
String -- Name of the newtype
String -- Name of the type its wrapping
toDocRow :: (Generic a, HasDatatypeInfo a) -> (Proxy a) -> MyRowRepresentation
toDocRow = <the part I'm struggling with>
newtype MyType0 = MyType0 Int16
newtype MyType1 = MyType0 Int8
newtype MyType2 = MyType0 Int32
newtype MyType3 = MyType0 Word8
main = do
let table = [
toDocRow (Proxy::MyType0),
toDocRow (Proxy::MyType1),
toDocRow (Proxy::MyType2),
toDocRow (Proxy::MyType3),
]
-- Do something to write `table` to disk.
Run Code Online (Sandbox Code Playgroud)
但是,我很难理解如何Generics/Data.Data与构造函数交互。这是我第一次使用 Haskell 区域,所以我尝试了以下代码,只是为了看看它是如何工作的:
{-# LANGUAGE DeriveGeneric #-}
module TmpTmpExport where
import RIO
import RIO.List.Partial (head)
import Text.Show.Pretty
import Data.String.Conversions (cs)
import Data.Data
newtype MyNewType = MyNewType Integer
deriving (Show)
deriving (Data, Typeable)
main :: IO ()
main = do
traceM $ cs $ "INSTANCE: " ++ (show $ dataTypeConstrs $ dataTypeOf $ (MyNewType 0))
traceM $ cs $ "INSTANCE constrType: " ++ (show $ constrType $ head $ dataTypeConstrs $ dataTypeOf $ (MyNewType 0))
traceM $ cs $ "INSTANCE constrType: " ++ (show $ dataTypeConstrs $ constrType $ head $ dataTypeConstrs $ dataTypeOf $ (MyNewType 0))
traceM $ cs $ "INSTANCE constrType: " ++ (show $ (fmap showConstr) $ dataTypeConstrs $ constrType $ head $ dataTypeConstrs $ dataTypeOf $ (MyNewType 0))
traceM $ cs $ "INSTANCE constrType: " ++ (show $ dataTypeConstrs $ constrType $ head $ dataTypeConstrs $ constrType $ head $ dataTypeConstrs $ constrType $ head $ dataTypeConstrs $ dataTypeOf $ (MyNewType 0))
return ()
Run Code Online (Sandbox Code Playgroud)
这给出了以下输出:
INSTANCE: [MyNewType]
INSTANCE constrType: DataType {tycon = "MyNewType", datarep = AlgRep [MyNewType]}
INSTANCE constrType: [MyNewType]
INSTANCE constrType: ["MyNewType"]
INSTANCE constrType: [MyNewType]
Run Code Online (Sandbox Code Playgroud)
我不认为我在一百万英里之外,但是通过阅读 的文档Data.Data并尝试各种功能,我无法弄清楚如何使用dataTypeConstrsand来“进入”新类型constrType,以便我可以创建table行喜欢:
table = [
(MyRowRepresentation "Type0" "Int16"),
(MyRowRepresentation "Type1" "Int8")
(MyRowRepresentation "Type2" "Int32")
(MyRowRepresentation "Type3" "Word8")
]
Run Code Online (Sandbox Code Playgroud)
我在概念上是否遗漏了newtype和之间的区别data,这可能与Data.Data,还是应该查看不同的工具/库有关?
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |