Data.HashTableを使ってみる。

Data.HashTable

  • new (key -> key -> Bool) -> (key -> Int32) -> IO (HashTable key val) 新しいハッシュ表を作る。最初の引数は key を比較する関数、2番目の引数は key を Int32 に変換する関数。(Int 用の hashInt、文字列用の hashString がある。)

参考:紫藤のページ Haskell のお勉強 10. 種々のデータ構造

> :m + Data.HashTable
-- key が Int、値が文字列の新規 HashTable
>  i <- new (==) hashInt :: IO (Data.HashTable.HashTable Int String)
> :t i --=> i :: HashTable Int String

-- key が文字列、値が文字列の新規 HashTable
> h <- new (==) hashString :: IO (Data.HashTable.HashTable String String)
> :t h --=> h :: Data.HashTable.HashTable String String

> insert h "key"  "value"  
> insert h "key2" "value2"
> insert h "key3" "value3"
> toList h --=> [("key","value"),("key3","value3"),("key2","value2")]
-- 検索してみる。
> Data.HashTable.lookup h "key2"  --=> Just "value2"
> Data.HashTable.lookup h "key10" --=> Nothing
-- 更新してみる。
> update h "key" "Hoge"           --=> True
> toList h --=> [("key","Hoge"),("key3","value3"),("key2","value2")]
-- 削除してみる。
> delete h "key3"
> toList h --=> [("key","Hoge"),("key2","value2")]
-- リストからHashTableに一気に変換。
> hs <- H.fromList Data.HashTable.hashInt [(1,300),(2,500),(3,700)]
> :t hs --=> hs :: HashTable Int Integer
> mapM (Data.HashTable.lookup hs) [0..5]
  --=> [Nothing,Just 300,Just 500,Just 700,Nothing,Nothing]

同じキーのデータを重複して insert するとどうなるか。

> insert h "key"  "value----------------"  
-- 重複して挿入された。
-- hash 値が衝突したときと同じ
> toList h
[("key","value----------------"),("key","value"),("key3","value3"),("key2","value2")]
-- 一応、検索も可能。
>  Data.HashTable.lookup h "key"
Just "value----------------"