assignment

This commit is contained in:
Michael Zhang 2018-02-20 05:19:49 -06:00
parent d071fa74c5
commit e82e05131c
No known key found for this signature in database
GPG key ID: A1B65B603268116B
3 changed files with 9 additions and 6 deletions

View file

@ -3,6 +3,7 @@ open Lexing
open Parser open Parser
open Types open Types
exception UnboundVariable of string
exception EvaluationComplete exception EvaluationComplete
(* (*
@ -31,7 +32,7 @@ let remove ctx name =
let rec lookup ctx name : Types.term = let rec lookup ctx name : Types.term =
match ctx with match ctx with
| [] -> print_endline ("unbound variable " ^ name); raise (Failure ("unbound variable " ^ name)) | [] -> raise (UnboundVariable name)
| (n, t)::tail -> | (n, t)::tail ->
if n = name then t else lookup tail name if n = name then t else lookup tail name
@ -71,12 +72,13 @@ let rec eval (ctx, t) =
let (s, t') = try_subst n t r in let (s, t') = try_subst n t r in
(*print_endline ("try_subst('" ^ n ^ "', " ^ (string_of_term t) ^ ", " ^ (string_of_term r) ^ ") = " ^ (if s then "true" else "false"));*) (*print_endline ("try_subst('" ^ n ^ "', " ^ (string_of_term t) ^ ", " ^ (string_of_term r) ^ ") = " ^ (if s then "true" else "false"));*)
if s then helper (ctx, t') (d + 1) else (ctx, t') if s then helper (ctx, t') (d + 1) else (ctx, t')
| _ -> (*print_endline "called EvaluationComplete"; *)raise EvaluationComplete
in try in try
let (ctx', t') = helper (ctx, t) 0 in let (ctx', t') = helper (ctx, t) 0 in
if t = t' then raise EvaluationComplete else if t = t' then raise EvaluationComplete else
eval (ctx', t') eval (ctx', t')
with EvaluationComplete -> (ctx, t) with
| UnboundVariable v -> print_endline ("unbound variable " ^ v); raise (Failure "")
| EvaluationComplete -> (ctx, t)
let _ = let _ =
try try
@ -91,8 +93,7 @@ let _ =
loop ctx' loop ctx'
| Types.Assign (n, t) -> | Types.Assign (n, t) ->
let (ctx', r) = eval (ctx, t) in let (ctx', r) = eval (ctx, t) in
(* bind the name *) loop (assign ctx' (n, r))
loop ctx'
in loop [] in loop []
with Lexer.Eof -> with Lexer.Eof ->
print_endline "^D"; print_endline "^D";

View file

@ -11,5 +11,6 @@ rule token = parse
| '(' { LParen } | '(' { LParen }
| ')' { RParen } | ')' { RParen }
| '.' { Dot } | '.' { Dot }
| "let" { Let }
| ['a'-'z' 'A'-'Z'] ['a'-'z' 'A'-'Z' '0'-'9' '_']* as s { Ident(s) } | ['a'-'z' 'A'-'Z'] ['a'-'z' 'A'-'Z' '0'-'9' '_']* as s { Ident(s) }
| eof { raise Eof } | eof { raise Eof }

View file

@ -7,6 +7,7 @@
%token Equal %token Equal
%token LParen %token LParen
%token RParen %token RParen
%token Let
%token <string> Ident %token <string> Ident
%token Lambda %token Lambda
@ -23,7 +24,7 @@ main:
| expr EOL { Types.Term($1) } | expr EOL { Types.Term($1) }
; ;
assign: assign:
| Ident Equal expr { Types.Assign($1, $3) } | Let Ident Equal expr { Types.Assign($2, $4) }
; ;
expr: expr:
| Ident { Types.TmVar($1) } | Ident { Types.TmVar($1) }