PageRenderTime 19ms CodeModel.GetById 11ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/fparsec/main/Samples/FSharpParsingSample/LexYaccVersion/interp.fs

http://github.com/sandersn/fing
F# | 58 lines | 42 code | 11 blank | 5 comment | 9 complexity | dca3c1bc5eed7ee5241e06cd8bf7d720 MD5 | raw file
 1
 2// Copyright (c) Microsoft Corporation 2005-2006.
 3// This sample code is provided "as is" without warranty of any kind.
 4// We disclaim all warranties, either express or implied, including the
 5// warranties of merchantability and fitness for a particular purpose.
 6//
 7
 8module Interp
 9
10open Ast
11open Microsoft.FSharp.Compatibility.OCaml
12
13type v = INT of int | FLOAT of float
14
15let printVal os v =
16    match v with
17    | INT n -> Printf.fprintf os "%d" n
18    | FLOAT f -> Printf.fprintf os "%g" f
19
20let rec prog (Prog l ) =
21    stmts (Hashtbl.create 10) l
22
23and stmts s l =
24    List.iter (stmt s) l
25
26and stmt s st =
27    match st with
28    | Assign (a,b) ->
29        Hashtbl.replace s a (expr s b)
30    | While (a,b) ->
31        while expr s a <> INT 0 do
32            stmt s b
33    | Seq l ->
34        stmts s l
35    | IfThen (g,t) ->
36        if (expr s g <> INT 0) then stmt s t
37    | IfThenElse (g,t,e) ->
38        if (expr s g <> INT 0) then stmt s t
39        else stmt s e
40    | Print (e) ->
41        Printf.printf "--> %a\n" printVal (expr s e)
42        stdout.Flush()
43
44and expr s e =
45    match e with
46    | Val n ->
47        if Hashtbl.mem s n then Hashtbl.find s n
48        else
49            Printf.eprintf "warning: location %s not defined\n" n;
50            INT 0
51    | Int n -> INT n
52    | Float f -> FLOAT f
53    | Decr e2 ->
54        match expr s e2 with
55        | INT n -> INT (n-1)
56        | FLOAT f -> failwith "cannot decrement a float"
57
58