From jmc at r-project.org  Wed May  4 18:27:57 2011
From: jmc at r-project.org (John Chambers)
Date: Wed, 04 May 2011 09:27:57 -0700
Subject: [Rd] General "nil" reference class object
In-Reply-To: <BANLkTik===MTEceVouu=P3v3yamC6T8U0w@mail.gmail.com>
References: <BANLkTik===MTEceVouu=P3v3yamC6T8U0w@mail.gmail.com>
Message-ID: <4DC17E8D.4020407@r-project.org>

Interesting idea.

One approach would be to test against the _environment_ of the prototype 
object in the class definition.  Since the initialize method for a 
reference class must call new.env(), one knows that a real object from 
the class has a different environment.  Using that fact one could have 
functions
   nullObject(Class)
to get the null, and
   isNullObject(x)
to test.

My feeling is that this approach is better for R than having one single 
nil object, because nullObject(Class) would still be a valid object from 
the class.

Something to mull over.
   John


On 5/4/11 6:09 AM, Jon Clayden wrote:
> Dear John and others,
>
> I've been wondering about whether there's any way to indicate a "nil"
> reference class object, which will represent "no value", and be tested
> for, but not fail the internal type checking. NULL is the obvious
> choice (or seems so to me), but can only be used if an explicit class
> union is created:
>
>> Foo<- setRefClass("Foo")
>> Bar<- setRefClass("Bar", fields=list(foo="Foo"))
>> Bar$new(foo=NULL)
> Error in as(value, "Foo") :
>    no method or default for coercing "NULL" to "Foo"
>> setClassUnion("FooOrNull", c("Foo","NULL"))
> [1] "FooOrNull"
>> Bar<- setRefClass("Bar", fields=list(foo="FooOrNull"))
>> Bar$new(foo=NULL)
> An object of class "Bar"
> <environment: 0x10392c4a0>
>> is.null(Bar$new(foo=NULL)$foo)
> [1] TRUE
>
> Other languages allow things like "MyClass object = null", and it
> seems to me that it would be helpful to have a value which will always
> give TRUE for "is(object,<AnyReferenceClassName>)", but will
> specifically indicate a nil reference. One possible ad-hoc solution is
> to define the "empty" object of a base class to be "nil" (see below),
> but it seems like it would be better to have a value specifically
> designed for this purpose.
>
>> nilObject<- Foo$new()
>> is.nilObject<- function (x) identical(x,nilObject)
>> Bar<- setRefClass("Bar", fields=list(foo="Foo"), methods=list(
> + initialize=function (foo=nilObject) { initFields(foo=foo) }))
>> is.nilObject(Bar$new()$foo)
> [1] TRUE
>
> Is there already something like this that I'm not aware of? If not,
> would it be possible and generally desirable to create it?
>
> All the best,
> Jon
>
>
> --
> Jonathan D Clayden, PhD
> Lecturer in Neuroimaging and Biophysics
> Imaging and Biophysics Unit
> UCL Institute of Child Health
> 30 Guilford Street
> LONDON  WC1N 1EH
> United Kingdom
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>



[Rd] General "nil" reference class object
John Chambers