Skip to content

Instantly share code, notes, and snippets.

@johnmyleswhite
Created September 6, 2014 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmyleswhite/fe3b89a20640fe154a20 to your computer and use it in GitHub Desktop.
Save johnmyleswhite/fe3b89a20640fe154a20 to your computer and use it in GitHub Desktop.
Type instability when using "generic" NA value
> type.unstable <- function(x) {
+ if (x > 0) {
+ return("foo")
+ } else {
+ return(NA)
+ }
+ }
>
> class(type.unstable(0))
[1] "logical"
> class(type.unstable(1))
[1] "character"
@smbache
Copy link

smbache commented Sep 6, 2014

How about this:

library(ensurer)

`: character` <- ensures_that(is.character(.))

# Here the unstableness will be caught ...
type.stable.bad <- function(x) `: character` ({
  if (x > 0) {
    "foo"
  } else {
    NA
  }
})

# And can be corrected.
type.stable <- function(x) `: character` ({
  if (x > 0) {
    # But his could be a insecure, relying on external data
    # but this function won't allow non-character return type.
    "foo" 
  } else {
    NA_character_
  }
})

Or more advanced typing:

`: square matrix` <- 
    ensures_that(NCOL(.) == NROW(.), 
                 is.numeric(.), 
                 is.matrix(.))

var_covar <- function(...) `: square matrix`({
    ...
})

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