Skip to content

Instantly share code, notes, and snippets.

@richierocks
Created August 21, 2019 20:45
Show Gist options
  • Save richierocks/a87c6f8aa5f05564c9529e02cfbfe8c2 to your computer and use it in GitHub Desktop.
Save richierocks/a87c6f8aa5f05564c9529e02cfbfe8c2 to your computer and use it in GitHub Desktop.
# Making the colon operator work with characters
# A response to https://twitter.com/carroll_jono/status/1162932405516193793
# This is a stupid implementation, since it will hurt performance of any other usage of :
# Better to do it in C or C++
# Make : into an S3 generic
`:` <- function(x, y, ...) {
UseMethod(":")
}
# For convenience
charToInt <- function(x) {
utf8ToInt(substring(x, 1, 1))
}
# Assume the input is UTF8
`:.character` <- function(x, y, ...) {
i <- charToInt(x)
j <- charToInt(y)
intToUtf8(i:j, multiple = TRUE)
}
# For any non-character input, leave : as it is
`:.default` <- function(x, y, ...) {
base::`:`(x, y, ...)
}
# Usage is, e.g.,
"a":"e"
"base":"tidy"
1:5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment