R: atom support, fixes for self-hosting.
[jackhill/mal.git] / r / printer.r
1 ..printer.. <- TRUE
2
3 if(!exists("..types..")) source("types.r")
4
5 .pr_list <- function(lst, print_readably=TRUE, join="") {
6 concatl(lapply(lst,
7 function(e) .pr_str(e, print_readably)), sep=join)
8 }
9
10 .pr_str <- function(exp, print_readably=TRUE) {
11 pr <- print_readably
12 switch(class(exp),
13 "List"={
14 paste("(", .pr_list(exp, pr, " "), ")", sep="", collapse="")
15 },
16 "Vector"={
17 paste("[", .pr_list(exp, pr, " "), "]", sep="", collapse="")
18 },
19 "HashMap"={
20 hlst <- list()
21 if (length(exp) > 0) {
22 for(k in ls(exp)) {
23 hlst[[length(hlst)+1]] <- k
24 hlst[[length(hlst)+1]] <- exp[[k]]
25 }
26 }
27 paste("{", .pr_list(hlst, pr, " "), "}", sep="", collapse="")
28 },
29 "character"={
30 if (print_readably) {
31 paste("\"",
32 gsub("\\n", "\\\\n",
33 gsub("\\\"", "\\\\\"",
34 gsub("\\\\", "\\\\\\\\", exp))),
35 "\"", sep="", collapse="")
36 } else {
37 exp
38 }
39 },
40 "Symbol"={ exp },
41 "nil"={ "nil" },
42 "logical"={ tolower(exp) },
43 "MalFunc"={
44 paste("(fn* ", .pr_str(exp$params,TRUE),
45 " ", .pr_str(exp$ast, TRUE), ")", sep="")
46 },
47 "function"={ "<#function>" },
48 "Atom"={
49 paste("(atom ", .pr_str(exp$val,TRUE), ")", sep="")
50 },
51 { toString(exp) })
52 }