gpt4 book ai didi

haskell - 在数据类型构造函数中使用类

转载 作者:行者123 更新时间:2023-12-03 09:45:53 25 4
gpt4 key购买 nike

目前我有这样的事情:

data MyData = SomeData | MoreData | EvenMore
data DataLists = DataLists [MyData] [MyData]

这让我显然可以做这样的事情:
myDataList :: DataLists
myDataList = DataLists [SomeData, MoreData] [EvenMore, SomeData]

但我想做这样的事情:
-- Static Module File:

class MyClass b where
evaluate :: b -> Int

data SomeData = SomeData
data MoreData = MoreData
data EvenMore = EvenMore

instance MyClass SomeData where
evaluate _ = 2
instance MyClass MoreData where
evaluate _ = 3
instance MyClass EvenMore where
evaluate _ = 4

data DataList = DataList [MyClass] [MyClass] -- Obviously this is wrong

我希望我的那部分代码保持静态。因为稍后我想使用该模块添加一些类型以放入数据列表中。我需要这个单独的,因为整个模块将用于 2 个不同的项目,我不想继续编辑它。
data MyVeryOwnData = MyVeryOwnData
--I should be able to make up as many datastructures as I want

instance MyClass MyVeryOwnData where
evaluate _ = 99

myList :: DataList
myList = DataList [MyVeryOwnData, SomeData] [SomeData, EvenMore]

我意识到我可以像这样简单地将 MyVeryOwnData 放在模块文件中:
data MyData = SomeData | MyVeryOwnData ...

instance MyClass MyData where
evaluate SomeData = 2
evaluate MoreData = 3
... etc.

但我不想这样做,因为正如我之前所说,我想添加任意数量的数据类型。

最佳答案

您正在寻找的是所谓的异构列表,haskell 主要以两种方式支持它们,ExistentialsGADTs .我向您展示了一个可运行的代码示例,它解决了存在主义的问题。

{-# LANGUAGE ExistentialQuantification #-}

class Eval b where
evaluate :: b -> Int

data SomeData = SomeData
data MoreData = MoreData
data EvenMore = EvenMore

instance Eval SomeData where
evaluate _ = 2
instance Eval MoreData where
evaluate _ = 3
instance Eval EvenMore where
evaluate _ = 4

data Evalable = forall a . Eval a => Evalable a

instance Eval Evalable where
evaluate (Evalable a) = evaluate a

pack :: Eval a => a -> Evalable
pack = Evalable

data DataLists = DataLists [Evalable] [Evalable]

getFirst :: DataLists -> [Evalable]
getFirst (DataLists xs ys) = xs

main = do
let dl = DataLists [pack SomeData, pack EvenMore] [pack MoreData]
print . map evaluate . getFirst $ dl

应该清楚可以加 instance Eval MyVeryOwnData在外部模块中,然后您可以 pack这些值使它们变为 Evalable然后您可以将它们放入您的 Datalists .

关于haskell - 在数据类型构造函数中使用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11858841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com