-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,40 @@ | ||
ハッシュマップを使う | ||
==================== | ||
|
||
任意のデータをキーとするマップを作りたいことがあります。 | ||
`unordered-containers`の`Data.HashMap`を使うと、`Hashable`をインスタンスにもつデータをキーとするマップを作成できます。 | ||
|
||
`User`というデータを`email`をキーとして扱うにはこのように書くことができます。 | ||
|
||
```haskell | ||
-- unordered-containers | ||
import qualified Data.HashMap.Strict as HashMap | ||
|
||
-- hashable | ||
import Data.Hashable (Hashable, hashWithSalt) | ||
|
||
data User = User { email :: String, name :: String } | ||
deriving (Eq, Show) | ||
|
||
instance Hashable User where | ||
hashWithSalt salt user = hashWithSalt salt $ email user | ||
``` | ||
|
||
`hashable`は`unordered-containers`の依存パッケージです。 | ||
|
||
`User`に`Hashable`インスタンスを定義して`hashWithSalt`を実装しています。 | ||
これで`User`を`HashMap`のキーとして使うことができます。 | ||
|
||
使ってみましょう。 | ||
|
||
```haskell | ||
-- unordered-containers | ||
> import qualified Data.HashMap.Strict as HashMap | ||
> alice = User "[email protected]" "Alice" | ||
> bob = User "[email protected]" "Bob" | ||
> users = HashMap.fromList [(alice, "Alice is nice"), (bob, "Bob is great")] | ||
> HashMap.lookup alice users | ||
Just "Alice is nice" | ||
> HashMap.lookup bob users | ||
Just "Bob is great" | ||
``` |