R: add step4_if_fn_do and step5_tco.
[jackhill/mal.git] / r / step2_eval.r
1 if(!exists("..readline..")) source("readline.r")
2 if(!exists("..types..")) source("types.r")
3 if(!exists("..reader..")) source("reader.r")
4 if(!exists("..printer..")) source("printer.r")
5
6 READ <- function(str) {
7 return(read_str(str))
8 }
9
10 eval_ast <- function(ast, env) {
11 if (is.symbol(ast)) {
12 env[[as.character(ast)]]
13 } else if (.list_q(ast)) {
14 new.listl(lapply(ast, function(a) EVAL(a, env)))
15 } else if (.vector_q(ast)) {
16 new.vectorl(lapply(ast, function(a) EVAL(a, env)))
17 } else {
18 ast
19 }
20 }
21
22 EVAL <- function(ast, env) {
23 #cat("EVAL: ", .pr_str(ast,TRUE), "\n", sep="")
24 if (!.list_q(ast)) {
25 return(eval_ast(ast, env))
26 }
27
28 # apply list
29 el <- eval_ast(ast, env)
30 f <- el[[1]]
31 return(do.call(f,el[-1]))
32 }
33
34 PRINT <- function(exp) {
35 return(.pr_str(exp, TRUE))
36 }
37
38 repl_env <- new.env()
39 repl_env[["+"]] <- function(a,b) a+b
40 repl_env[["-"]] <- function(a,b) a-b
41 repl_env[["*"]] <- function(a,b) a*b
42 repl_env[["/"]] <- function(a,b) a/b
43
44 rep <- function(str) return(PRINT(EVAL(READ(str), repl_env)))
45
46 repeat {
47 line <- readline("user> ")
48 if (is.null(line)) { cat("\n"); break }
49 tryCatch({
50 cat(rep(line),"\n", sep="")
51 }, error=function(err) {
52 cat("Error: ", get_error(err),"\n", sep="")
53 })
54 # R debug/fatal with tracebacks:
55 #cat(rep(line),"\n", sep="")
56 }