プログラミングの基礎 第 7 章 組とパターンマッチ
少し間が空いたけど、再開する。
7 章から 9 章まではデータ構造の話みたい。
7.1 組の構文
2 つ以上の様々な型の値を組み合わせて「組」というデータ構造を表現出来る。
構造体みたいな感じ?
# (3.14, 2.71);; - : float * float = (3.14, 2.71) # (10, "str");; - : int * string = (10, "str") # (1, 'a', false);; - : int * char * bool = (1, 'a', false) # ((((3.13, 1), 1), 3), true);; - : (((float * int) * int) * int) * bool = ((((3.13, 1), 1), 3), true)
7.2 パターンマッチ
パターンマッチの構文
match 式 with パターン -> 式
注意。
- パターン変数は互いに異なる変数でなくてはならない
- パターン変数と与えられる組の型は同じでなくてはならない
# let test = (1, 2, 3);; val test : int * int * int = (1, 2, 3) # match test with (a, b) -> a + b;; Characters 20-26: (a, b) -> a + b;; ^^^^^^ Error: This pattern matches values of type 'a * 'b but is here used to match values of type int * int * int
7.3 構造データに対するデザインレシピ
組を引数に取る関数はほぼ必ず組の要素を取り出す match 文から始まるはず。だからテンプレートを用意しておけば便利、という話。