簡體   English   中英

在Haskell中實現一個簡單的關聯映射

[英]Implementing a simple associative map in Haskell

在這個時期我正在學習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]

暫無
暫無

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

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