Pseudocode to string - unparsed and unevaluated function input

Viewed 52

How does one preserve pseudocode unparsed and unevaluated, turning it into a string?

f(if (?length() != 0) ?task <- ?task[-1])

# wanted output
"if (?length() != 0) ?task <- ?task[-1]"

substitute, quote, deparse1, sys.call()[-1], expression (@IRTFM), as a formula ~{...} give the wrong result,

f <- function(...) deparse1(substitute(...))

# gives
#> [1] "if (`?`(length() != 0)) `?`(task <- `?`(task[-1]))"

An approach that works in interactive (RStudio, RGui) environments, and terminal, but not in a reprex::reprex() (...?). Not ideal because history file might be large.

f <- function(...) {
    file <- tempfile(fileext = ".txt")
    savehistory(file)
    s = tail(readLines(file), 1)
    substring(s, 3, nchar(s) - 1)
}

f(if (?length() != 0) ?task <- ?task[-1])
#> [1] "if (?length() != 0) ?task <- ?task[-1]"

Background
I (naively) wanted to make R6 syntax a bit easier on the eyes while keeping its syntax highlighting.

# cluttered syntax, if everything is private$ or self$, none of it has to be
R6::R6Class(
    private = list(
        task = list(),
        length = \() base::length(private$task)
    ),
    public = list(
        initialize = \(...) private$task <- list(...),
        add = \(x) private$task <- c(private$task, x),
        rm = \() if (private$length() != 0) private$task <- private$task[-1]
    )
)

R6::R6Class(
    private = list(
        task = list(),
        length = \() base::length(?task)
    ),
    public = list(
        initialize = \(...) ?task <- list(...),
        add = \(x) ?task <- c(?task, x),
        rm = \() if (?length() != 0) ?task <- ?task[-1]
    )
)
0 Answers
Related