在Haskell中实现以下字典:
module TreeDict (Dict, empty, insert, lookup) where
import Prelude hiding(lookup)
data Dict k v = Empty | Node { key :: k, val :: v, left :: Dict k v, right :: Dict k v }
deriving (Eq, Show)
empty :: Dict k v
empty = Empty
insert :: (Ord k) => k -> v -> Dict k v -> Dict k v
insert k v Empty = Node k v empty empty
insert k v d
| k < key d = Node (key d) (val d) (insert k v (left d)) (right d)
| k > key d = Node (key d) (val d) (left d) (insert k v (right d))
| otherwise = Node k v (left d) (right d)
lookup :: (Ord k) => k -> Dict k v -> Maybe v
lookup k Empty = Nothing
lookup k d
| k < key d = lookup k (left d)
| k > key d = lookup k (right d)
| otherwise = Just (val d)
我想编写一个类似于insert的函数,它允许我将给定键插入树的次数保持为一个值(但仅限Ord k
类)。
例如:对于列表[aa,bb,aa,aa],我的字典会保留:{aa - &gt; 3,bb - &gt; 1}。
知道如何调整我的代码吗?