2

Consider the function below:

foo <- function (a.list, index = NULL) {
  if (is.null(index)) {
    a.list[]
  }
  else {
    a.list[index]
  }
}

I'd like to know if there's some value EMPTY_INDEX for the definition of foo2 below:

foo2 <- function (a.list, index = EMPTY_INDEX) {
  a.list[index]
}

...that would render foo2 equivalent to foo.

kjo
  • 33,683
  • 52
  • 148
  • 265
  • 2
    `index = seq_along(a.list)`? – joran Sep 27 '16 at 19:05
  • doesn't `index = TRUE` work? – Shape Sep 27 '16 at 19:07
  • @Shape I believe that would result in something different in the corner case where `a.list` is an empty list. But I confess to being a bit in the dark as to the broader goals of the OP, so maybe that doesn't matter. – joran Sep 27 '16 at 19:12
  • 2
    just leave no default value of index in foo2? and leave index missing if you want the whole list: `foo2 <- function (a.list, index) a.list[index]; identical(foo(1:10, NULL), foo2(1:10))` – rawr Sep 27 '16 at 19:15
  • 1
    You might get some ideas from [here](http://stackoverflow.com/questions/17750893/how-to-pass-nothing-as-an-argument-to-for-subsetting) and [here](http://stackoverflow.com/questions/17751862/create-a-variable-length-alist) – alexis_laz Sep 27 '16 at 20:14
  • @rawr: AFAICT, your idea works really well; shockingly so, IMO, since I'm used to Python's conventions, whereby omitting an argument for which no default is specified in the function's definition results in an error. Care to post your solution as an answer? – kjo Sep 28 '16 at 11:23

0 Answers0