Skip to content

Commit

Permalink
Complete description of pattern-matching by the labels of the constru…
Browse files Browse the repository at this point in the history
…ctor fields
  • Loading branch information
igrep committed Apr 28, 2024
1 parent 3c9d773 commit 1fb0977
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions assets/18.md
Expand Up @@ -907,12 +907,58 @@ ghci| formatEntry (Entry { category = cat, price = pri }) = cat ++ ": " ++ show
ghci| :}
```

<!--
```haskell
-- ... さっきと同様に動作確認します ...
ghci> entry = Entry "" 999999999999999
ghci> formatEntry entry
"<Unknown category>: 999999999999999"
ghci> entry = Entry "Magazine" 120
ghci> formatEntry entry
"Magazine: 120"
```
-->

パターンマッチしている部分のみ切り出してみます:

```haskell
Entry { category = "", price = pri }
Entry { category = cat, price = pri }
```

最初に紹介したパターンマッチ(`(Entry "" pri)``(Entry cat pri)`)と異なり、

1. まず値コンストラクター`Entry`の後ろに、ブレースで囲ってパターンマッチするレコードラベルや変数を列挙しています
2. そして、レコードラベルと変数(あるいはマッチさせたい値)の間に`=`を書いて結びつけます

このように書くことで、先程と同様に`category``price`の値をそれぞれ`cat``pri`に割り当てたりする`formatEntry`を定義できます。

レコードラベルを使ったパターンマッチの大きなアドバンテージは、フィールドの順番に依存しないことです。従って、`formatEntry`関数は次のように`category``price`をマッチさせる順番を入れ替えても同じように振る舞います:

```haskell
ghci> :{
ghci| formatEntry :: Entry -> String
ghci| formatEntry (Entry { price = pri, category = "" }) = "<Unknown category>" ++ ": " ++ show pri
ghci| formatEntry (Entry { price = pri, category = cat }) = cat ++ ": " ++ show pri
ghci| :}
```

<!--
```haskell
-- ... 動作確認 ...
ghci> entry = Entry "" 999999999999999
ghci> formatEntry entry
"<Unknown category>: 999999999999999"
ghci> entry = Entry "Magazine" 120
ghci> formatEntry entry
"Magazine: 120"
```
-->

##### おまけ: パターンマッチと値の定義

hoge

#### タプルに対する関数の引数でのパターンマッチ

便利なサンプルが[`Prelude`モジュール][6]にいくつかある。
Expand Down

0 comments on commit 1fb0977

Please sign in to comment.