[Rd] formals() adds 0 to complex function arguments

Duncan Murdoch murdoch.duncan at gmail.com
Mon Jan 20 00:00:57 CET 2014


On 14-01-19 4:45 PM, Duncan Murdoch wrote:
> On 14-01-19 4:16 PM, peter dalgaard wrote:
>> It's not formals() that is doing you in. Rather, it is a conspiration between two things:
>> (a) R always displays complex constants as x+yi, even if x is zero and (b) there really is no way to specify complex constants with non-zero  real part, i.e. 1+2i is a sum of a real and and imaginary complex constant. You can see the effect already at
>>
>>> quote(1+2i)
>> 1 + (0+2i)
>>
>>
>>> q <- quote(1+2i)
>>> q[[1]]
>> `+`
>>> q[[2]]
>> [1] 1
>>> q[[3]]
>> [1] 0+2i
>>> str(q)
>>    language 1 + (0+2i)
>>> str(q[[3]])
>>    cplx 0+2i
>>
>> Someone might want to fix this by implementing a full syntax for complex constants, but meanwhile, I think a passable workaround could be
>
> That might be nice to do.  Not sure if it's easy or hard...

I think it's hard.  After seeing the 1, when the parser gets a "+", it's 
not clear whether you're in the middle of a complex number or some other 
kind of sum.  And since users can redefine "+", it could be a really 
different kind, even if it's followed by 2i.

Duncan Murdoch

>
>>
>>> formals(test)$a <- 1+2i
>>> args(test)
>> function (a = 1+2i)
>> NULL
>>> test
>> function (a = 1+2i)
>> {
>> }
>>
>>
>> Or maybe, less sneaky
>>
>> Cplx_1plus2i <- 1+2i
>> test <- function(a = Cplx_1plus2i){}
>
> Less sneaky, but a tiny bit different due to scoping issues:  if the
> function happens to assign something to a local variable Cplx_1plus2i
> before evaluating a, the local variable will be used rather than the
> global one.
>
> Duncan Murdoch
>



More information about the R-devel mailing list