在此期间,我正在学习Haskell,但我在解决一个简单的练习时遇到了问题。
我想写一个简单的关联地图数据结构来锻炼自己。
这是我到目前为止编写的代码:
-- It represents a simple ordered couple in the form (key, value)
data Element a b = Element (a, b)
deriving (Show)
-- It represents a (unordered) list of elements in the form (key, value)
data Dictionary a b = Dictionary [Element a b]
deriving (Show)
-- It represents a simple dictionary which will be used for my tests
t :: Dictionary Char Int
t = Dictionary [Element ('a', 1), Element ('b', 2), Element ('a', 3)]
现在我正在尝试编写一个简单的方法来返回形式为 (a, b) 的夫妻列表。我这样做是为了锻炼自己并提供一个简单的函数,该函数对其他方法(查找等)很有用。
我已经写了这段代码,但我知道这是错误的:
couples :: Dictionary a b -> [(a, b)]
couples (Dictionary t) = [(k , v) | (k, v) <- t]
问题在于,显然"t"不是一对列表:它由一个元素列表组成,这些元素列表由类型构造函数"Element"后跟有序对组成。
如何"摆脱"元素"类型构造函数?我不知道。。。
提前谢谢你。
只需在模式匹配中添加 Element 构造函数即可。
couples :: Dictionary a b -> [(a, b)]
couples (Dictionary t) = [(k , v) | (Element (k, v)) <- t]