Skip to content

Instantly share code, notes, and snippets.

@wch
Last active June 8, 2018 19:56
Show Gist options
  • Save wch/9fca93ab0e2b7b690691 to your computer and use it in GitHub Desktop.
Save wch/9fca93ab0e2b7b690691 to your computer and use it in GitHub Desktop.
car, cdr, and push for pairlists in R
library(inline)
library(microbenchmark)
car <- cfunction(c(x = "pairlist"), '
if (x == R_NilValue)
return R_NilValue;
if (TYPEOF(x) != LISTSXP)
error("x must be a pairlist");
return CAR(x);
')
cdr <- cfunction(c(x = "pairlist"), '
if (x == R_NilValue)
return R_NilValue;
if (TYPEOF(x) != LISTSXP)
error("x must be a pairlist");
return CDR(x);
')
push <- cfunction(c(x = "pairlist", value = 'ANY'), '
if (x != R_NilValue && TYPEOF(x) != LISTSXP)
error("x must be a pairlist");
return CONS(value, x);
')
n <- 1e4
l <- as.list(1:n)
p <- as.pairlist(1:n)
microbenchmark(
# Get head item
z <- l[[1]],
z <- p[[1]],
z <- car(p),
# Add to head
z <- c(1, l),
z <- c(1, p),
z <- push(p, 1),
# Add to tail
z <- c(l, 1),
z <- c(p, 1),
# Remove from head
z <- l[-1],
z <- p[-1],
z <- cdr(p),
# Remove from tail
z <- l[seq_len(length(l) - 1)],
z <- p[seq_len(length(p) - 1)],
unit = "us"
)
@xappppp
Copy link

xappppp commented Dec 29, 2016

Any where you post the benchmark result?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment