Reputation: 11128
I don't know , if this is the correct place to ask subjective questions and I am fairly new to R, but i am really confused at this time.I was going through R-Language reference and found two objects by running typeof(is.na)
and typeof(mean)
which returned "builtin" and "closure" respectively on R prompt. I don't know what does it mean, I went to this site after searching, http://www.r-bloggers.com/closures-in-r-a-useful-abstraction/ , but unable to understand , Can anyone help me in understanding "closure" and "builtin" in some layman terms?
Upvotes: 4
Views: 794
Reputation: 132706
From help("closure")
:
This type of function is not the only type in R: they are called closures (a name with origins in LISP) to distinguish them from primitive functions.
From help(".Primitive")
:
a ‘primitive’ (internally implemented) function.
"internally implemented" is just a different term for "builtin".
Both (closures and primitives) are functions in R. A primitive function is implemented exclusively in C (with a special calling mechanism), a closure (mostly) in R.
Another distinction between them is, that a closure always has an environment associated with it (see the language definition). That's actually pretty much the definition of "closure".
Upvotes: 8
Reputation: 603
function clousures, or simply functions, are made of three basic components: formals, body and environment.
The environment, or better the enclosing environment, of a function is the environment where the function is created and functions do remember it ...
> typeof(mean)
[1] "closure"
> environment(mean)
<environment: namespace:base>
> environment(function(x){x+1})
<environment: R_GlobalEnv>
Primitives, as opposite to closures, do not have an environment:
> typeof(sum)
[1] "builtin"
> environment(sum)
NULL
In practice, closures and Primitives, differ in the way arguments are passed to the internal function.
If we want to check if a function is a closure or primitive, we may use:
> is.primitive(sum)
[1] TRUE
> is.primitive(mean)
[1] FALSE
Upvotes: 3