Tags

Someone asked recently how lambda.r deals with NAs 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 NAs 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 NAs works as expected:

> f(c(1,2,3,NA,5))
  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 NAs 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)
 "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_)
 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')
{"ft_lang_label":"__label__en","ft_lang_prob":0.8173875,"math_prob":0.92959166,"size":1305,"snap":"2019-43-2019-47","text_gpt3_token_len":344,"char_repetition_ratio":0.09607994,"word_repetition_ratio":0.0,"special_character_ratio":0.25823754,"punctuation_ratio":0.15438597,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9602528,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-10-17T10:55:39Z\",\"WARC-Record-ID\":\"<urn:uuid:551f0716-945c-4791-87cf-acf48c72828b>\",\"Content-Length\":\"70916\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:6f621716-b01f-4f82-adb9-11075f69662b>\",\"WARC-Concurrent-To\":\"<urn:uuid:a2ff30ad-9400-41cf-9098-dd3041211c24>\",\"WARC-IP-Address\":\"192.0.78.25\",\"WARC-Target-URI\":\"https://cartesianfaith.com/2015/01/15/type-constraints-and-nas-in-lambda-r/\",\"WARC-Payload-Digest\":\"sha1:SIJUB57URAX5QTNPRWRXL5A2DGIGQWFY\",\"WARC-Block-Digest\":\"sha1:CXWKBXLQSCT2RRBUGCVO4LUYVAADC66O\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-43/CC-MAIN-2019-43_segments_1570986673538.21_warc_CC-MAIN-20191017095726-20191017123226-00512.warc.gz\"}"}