LoginSignup
3
0

More than 5 years have passed since last update.

match withはfunctionで書き直せるじゃないか

Posted at

足し算できる言語を作ります。

type e = EInt | EAdd of e * e

let rec eval e =
  match e with
  | EInt(i) -> i
  | EAdd(e1,e2) -> eval e1 + eval e2

let () =
  Printf.printf "%d\n" (eval (EAdd(EInt 1, EInt 2)))

足し算できる言語を作ります。これは、以下のようにかきますよね。

type e = EInt | EAdd of e * e

let rec eval =
  function
  | EInt(i) -> i
  | EAdd(e1,e2) -> eval e1 + eval e2

let () =
  Printf.printf "%d\n" (eval (EAdd(EInt 1, EInt 2)))

ところで、|>演算子を使えば

type e = EInt | EAdd of e * e

let rec eval e =
  e |> function
  | EInt(i) -> i
  | EAdd(e1,e2) -> eval e1 + eval e2

let () =
  Printf.printf "%d\n" (eval (EAdd(EInt 1, EInt 2)))

と書くことができます。パーシャル関数が使えて|>演算子に相当するものがあれば、マッチ構文はわざわざ作る必要が無いように思います。

言語を作る場合には、パーシャル関数を考えさえすれば、パターンマッチの構文は不要なのではないかという話でした。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0