Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Created January 28, 2012 17:18
Show Gist options
  • Save martintrojer/1695088 to your computer and use it in GitHub Desktop.
Save martintrojer/1695088 to your computer and use it in GitHub Desktop.
scheme-fsharp
let rec eval (env:Map<string,expression> list) expr =
match expr with
| NullExpr -> failwith "invalid interpreter state"
| Combination([]) -> failwith "invalid combination"
| Combination(h::t) ->
match eval env h with
| (nenv, Procedure(f)) -> apply f t env
| (nenv, Function(args, code)) ->
let newenv =
try List.fold2 bindArg (expandEnv nenv) args t
with ex -> failwith "invalid number of arguments"
evalExprs newenv code
| (nenv, expr) -> (nenv, expr)
| Procedure(f) -> (env, Procedure(f))
| Function(args, code) -> failwith "invalid function call"
| Value(v) -> (env, Value(v))
| List(v) -> (env, List(v))
| Symbol(s) ->
match lookup env s with
| Some(e) -> (env, e)
| None -> failwith (sprintf "unbound symbol '%A'" s)
and apply f args env = f env args
mtscheme v0.1
null
> (define (factorial x) (if (= x 0) 1 (* x (factorial (- x 1)))))
null
> (factorial 9)
362880.00
>
let rec commandLoop (env, res) =
match res with
| Value(Number(v)) -> printfn "%4.2f\n> " v
| Value(Name(v)) -> printfn "%s\n> " v
| Value(Boolean(v)) -> printfn "%b\n> " v
| List(l) -> printfn "%s" (listToStr l)
| _ -> printfn "null\n> "
try Console.ReadLine()
|> List.ofSeq
|> parse
|> List.head
|> (eval env)
|> commandLoop
with ex -> commandLoop (env, Value(Name(ex.Message)))
type Expression =
| NullExpr
| Combination of Expression list
| List of ListType list
| Function of ListType list * Expression list
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment