Browse files

4-2. 関数の処理の続き

  • Loading branch information...
1 parent 767c049 commit 5e04de49fc18cc476b4264c3cfcb7e2c9d1a07c4 @tomykaira committed Mar 19, 2012
Showing with 11 additions and 2 deletions.
  1. +7 −0 eval.ml
  2. +4 −2 test.ml
View
7 eval.ml
@@ -9,6 +9,7 @@ let rec lookup x env = match env with
let string_of_value value = match value with
| IntVal v -> string_of_int v
| BoolVal v -> if v then "true" else "false"
+| FunVal (param, body, env) -> "Fun " ^ param
| _ -> failwith "unknown value"
let rec print_env env = match env with
@@ -53,6 +54,12 @@ let rec eval e env =
| BoolLit b -> BoolVal b
| Var x -> lookup x env
| Let (x, v, e) -> eval e (ext env x (eval v env))
+ | Fun (x, e) -> FunVal(x, e, env)
+ | App (e1, e2) ->
+ (match eval e1 env with
+ | FunVal (param, body, env1) ->
+ eval body (ext env1 param (eval e2 env))
+ | _ -> failwith "function value expected")
| _ -> failwith "unknown expression"
let new_eval e = eval e emptyenv
View
6 test.ml
@@ -8,15 +8,17 @@ let _t title exp e =
else "FAILURE: exp: " ^ (string_of_value exp) ^ " act: " ^ (string_of_value result))
let _ =
- (_t "四則演算" (IntVal(4*1*10+5)) (Plus (Times (Times(IntLit 4, IntLit 1), IntLit 10), IntLit 5)));
+ ((_t "四則演算" (IntVal(4*1*10+5)) (Plus (Times (Times(IntLit 4, IntLit 1), IntLit 10), IntLit 5)));
(_t "if" (IntVal 2) (If (BoolLit true, IntLit 2, IntLit 4)));
(_t "if" (IntVal 4) (If (BoolLit false, IntLit 2, IntLit 4)));
(_t "eq - true" (BoolVal true) (Eq (IntLit 4, IntLit 4)));
(_t "eq - false" (BoolVal false) (Eq (IntLit 4, IntLit 6)));
(_t "greater" (BoolVal true) (Greater(IntLit 5, IntLit 3)));
(_t "let" (IntVal 100) (Let("x", IntLit 100, Var "x")));
(_t "let: 内側の定義で上書きされる" (IntVal 200) (Let("x", IntLit 100, Let("x", IntLit 200, Var "x"))));
- (_t "let: 以前に定義した変数をつかって定義できる" (IntVal 400) (Let("x", IntLit 100, Let("y", Plus(IntLit 200, Var "x"), Plus(Var "x", Var "y")))))
+ (_t "let: 以前に定義した変数をつかって定義できる" (IntVal 400) (Let("x", IntLit 100, Let("y", Plus(IntLit 200, Var "x"), Plus(Var "x", Var "y")))));
+ (_t "lambda func" (IntVal 20) (Let ("fun", Fun("x", Plus(Var "x", IntLit 10)), App(Var "fun", IntLit 10))));
+ )
(* eval (Plus (Times (Div(IntLit 4, IntLit 0), IntLit 10), IntLit 5)) : デフォルトのエラーを利用 *)

0 comments on commit 5e04de4

Please sign in to comment.