Real World Haskell - 第3章 Part4 Pattern matching
Real World Haskell で Haskell を継続的に勉強中。
Defining Types, Streamlining Functions
Chapter 3. Defining Types, Streamlining Functions
Pattern matching
myNot True = False myNot False = True
- Haskell では上記のような式の組み合わせで 1つの関数を定義できる
- 異なる input のパターンを複数書く
sumList (x:xs) = x + sumList xs sumList [] = 0
- パターンマッチは書いた順におこなわれる
- 順番重要
- underscore で wild card になる
- wild card は変数のように振る舞うが値は bind されない
bookID (Book id title authors) = id bookTitle (Book id title authors) = title bookAuthors (Book id title authors) = authors
nicerID (Book id _ _ ) = id nicerTitle (Book _ title _ ) = title nicerAuthors (Book _ _ authors) = authors
- パターンを書くときは全てのケースにマッチできるか気をつける
- GHC には -fwarn-incomplete-patterns オプションがある
参考