Skip to Content
Course content

129: Building a Simple DSL in R

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Wait, isn't a DSL just a bunch of functions? Why do I need a specific "language"?

That's the most common point of confusion when people first encounter the term. If you write five functions to clean text, you've written a library. But when you design those functions so that the way they are combined creates a new, readable grammar for a specific problem, you're moving into DSL territory. Think about dplyr. It isn't just a collection of verbs; it's a language for data manipulation. It allows you to express "what" you want to happen rather than "how" to loop through the data.

I usually suggest building a DSL when you find yourself writing the same sequence of nested functions over and over. For this lesson, let's imagine we're building a "Text Scrubbing" DSL. Instead of writing clean_whitespace(remove_punct(to_lower(text))), we want something that feels like a recipe.

How do I make the syntax feel "clean" and avoid nesting functions ten levels deep?

In R, the secret sauce is often Non-Standard Evaluation (NSE) or simply leveraging the pipe. But if you want to build a true DSL, you can create a "wrapper" that takes a list of instructions and executes them sequentially. I prefer this approach because it separates the definition of the process from the execution.

Check out this pattern. We'll create a scrub_text function that acts as our engine, and a few small helper functions that return "instruction" objects (in this case, just names or small lists):

# Our "grammar" helpers
lower_case <- function() list(op = "lower")
remove_digits <- function() list(op = "digits")
replace_word <- function(old, new) list(op = "replace", old = old, new = new)

# Our DSL Engine
scrub_text <- function(text, ...) {
  steps <- list(...)
  
  for (step in steps) {
    if (step$op == "lower") {
      text <- tolower(text)
    } else if (step$op == "digits") {
      text <- gsub("[0-9]", "", text)
    } else if (step$op == "replace") {
      text <- gsub(step$old, step$new, text)
    }
  }
  return(text)
}

# Now the usage feels like a configuration, not a nesting nightmare
my_text <- "User123 says HELLO World!"
scrub_text(my_text, 
           lower_case(), 
           remove_digits(), 
           replace_word("hello", "hi"))
# Result: "user says hi world!"

Notice how the user of scrub_text doesn't have to worry about the order of arguments or nested parentheses. They just list the operations they want.

Can I actually capture the commands as data before running them?

Yes, and this is where R gets really powerful. If you use substitute(), you can capture the code the user wrote without actually running it. This is how you build "lazy" DSLs—where you define a pipeline once and apply it to a thousand different strings later.

I've found that this is incredibly useful for auditing. If you capture the expression, you can print out exactly what the "recipe" was before you execute it. Here is a simplified version of how you might capture a sequence of calls:

# A function that captures the 'recipe' as an expression
define_recipe <- function(expr) {
  substitute(expr)
}

# Define it once
my_recipe <- define_recipe(
  lower_case() + remove_digits()
)

print(my_recipe) 
# This prints the code itself, not the result!

To make the + work like that, you'd need to overload the operator or use a custom pipe, but for a simple DSL, the list(...) approach I showed earlier is usually the sweet spot between power and maintainability. Don't over-engineer it unless you're building a package for thousands of people; usually, a clean wrapper is all you need.




📋 Practical Task

Exercise: Building a Financial Formatting DSL

You need to create a simple DSL that allows a financial analyst to format a vector of raw numbers into "report-ready" strings. The analyst doesn't know R well, so the syntax must be declarative.

  • Create three helper functions: round_to(n), add_currency(symbol), and bold_text(). Each should return a list describing the operation.
  • Create an engine function called format_finance() that takes a numeric vector and a set of these helper functions (using ...).
  • The engine should apply the operations in the order they are listed.
    • round_to should use round().
    • add_currency should prepend the symbol to the number.
    • bold_text should wrap the resulting string in Markdown bold tags (e.g., **12.34**).

Test your DSL with this call:
format_finance(c(123.456, 789.101), round_to(2), add_currency("$"), bold_text())
Expected Output: "**$123.46**" "**$789.10**"

Rating
0 0

There are no comments for now.

to be the first to leave a comment.