Data.HashTable を使ってみる。

Haskell のお勉強 10. 種々のデータ構造を参考にData.HashTable を使ってみる。


Prelude> :m + Data.HashTable
Prelude Data.HashTable> :set prompt "> "
>
> h <- new (==) hashString :: IO (HashTable String String)
> :t h
h :: HashTable String String

> insert h "key" "val"
> insert h "123" "hogehoge"
> toList h
[("key","val"),("123","hogehoge")]

> Data.HashTable.lookup h "key"
Just "val"
> Data.HashTable.lookup h "hello"
Nothing

> update h "123" "update!"
True
> Data.HashTable.lookup h "123"
Just "update!"
> toList h
[("key","val"),("123","update!")]

> delete h "key"
> toList h
[("123","update!")]

> hash <- fromList hashString [("abcd","efg"),("hello","world")]

> :t hash
hash :: HashTable String [Char]

> insert hash "newKey" "newVal"
> insert hash "newKey2" "newVal2"
> toList hash
[("abcd","efg"),("hello","world"),("newKey2","newVal2"),("newKey","newVal")]
> Data.HashTable.lookup hash "newKey"
Just "newVal"