2012-12-05 30 views
1

在這段時間我正在學習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」是不是情侶列表:它是由是由組成元素的列表組成一個類型構造器「元素」,後面是一個有序的對。

我怎麼能擺脫「元素」類型的構造函數?我不知道...

在此先感謝您。

+0

正如旁白一樣,它被稱爲「元組」,不是情侶,而是情侶的發音韻。不要挑剔,但這可以幫助避免混淆。 – RonaldBarzell

+0

您在執行過程中有多少迴旋餘地?我認爲這樣做有更簡單的方法。 – RonaldBarzell

+0

我明白你想練習,但只是FYI:在Data.List中有一個函數'lookup :: Eq k => k - > [(k,v)] - > Maybe v'已經這樣做了。 –

回答

4

只需在模式匹配中添加Element構造函數即可。

couples :: Dictionary a b -> [(a, b)] 
couples (Dictionary t) = [(k , v) | (Element (k, v)) <- t] 
+0

好的,謝謝。我想我可以在方程的左邊部分進行模式匹配。我必須在這些事情中鍛鍊。 – JohnQ

+0

@JohnQ你也應該接受德克的回答,因爲它回答你的問題 – jozefg

+0

當然是的!我沒有太多的StackOverflow經驗。現在我已經接受它作爲答案:) – JohnQ