# Type constraints and NAs in lambda.r

**Cartesian Faith » R**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Someone asked recently how lambda.r deals with `NA`

s in type constraints. Type constraints are optional decorations on a function that enforces the type for each function argument. The short answer is that since `NA`

s are typed, they work just like other values.

Consider the toy function

f(x) %::% numeric : numeric f(x) %as% x^2

Calling `f`

with a vector containing `NA`

s works as expected:

> f(c(1,2,3,NA,5)) [1] 1 4 9 NA 25

What happens if you pass a scalar `NA`

? Now things get interesting.

> f(NA) Error in UseFunction(f, "f", ...) : No valid function for 'f(logical)'

Lo, we get an error! This is an artifact of how R deals with `NA`

values. Since `NA`

s are typed, normally the type can be inferred by the other values in a vector. However, if `NA`

is the only value i.e. a scalar, no information is available. Therefore R must choose some default value, which happens to be logical.

> class(NA) [1] "logical"

To get around this situation, one can simply use the explicitly typed `NA`

constant for the type you care about. In this case, it’s `NA_integer_`

.

> f(NA_integer_) [1] NA

See `?NA`

for more information on the mechanics and behavior of `NA`

.

`lambda.r`

is available on CRAN. The most recent version is on github and can be installed using devtools:

library(devtools) install_github('lambda.r','zatonovo')

**leave a comment**for the author, please follow the link and comment on their blog:

**Cartesian Faith » R**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.