Skip to content
Prev 459 / 10988 Next

[Rcpp-devel] Good idioms for creating a named list?

Hello,

I have now commited make_list as a set of templates taking variable 
number of arguments and creating named generic vectors. There is again 
some code bloat involved and it handles up to 20 arguments. (this is not 
painful to make it 50 or 100, but I think 20 is good enough for now).

For example (see more of this in the runit.make.list.R file):

fx <- cfunction(signature(),'
		return make_list(
			Named("a") = 1 ,
			Named("b") = 2 ,
			Named("c") = "foobar",
			Named("d") = 4.0 ) ;	
	',
	Rcpp = TRUE, includes = "using namespace Rcpp; " )
	
I've also added the Argument class, which is somewhat similar to Named, 
except that it does not hold the object (only its name) and it is the 
templated operator= that makes a Named object from it. This means that 
the code above can be replaced by this:

		return make_list(
			Argument("a") = 1 ,
			Argument("b") = 2 ,
			Argument("c") = "foobar",
			Argument("d") = 4.0 ) ;	


But it can also be used to first declare a set of arguments that a given 
package uses a lot, and then just use them with a nice construct. For 
example :

// declare the arguments:
// maybe in some header file
Argument x("x"), y("y") ;

// use them:
make_list( x = 2, y = "foo" ) ;
Language call( "somefunction", x = 2, y = "foo" ) ;
Pairlist pl( x = 2, y = 3 )
Function f("somefunction" ) ;
f( x = 2, y = 3 )


For example minqa uses the same arguments several times : "par", "fval", 
"feval", "intpval", so maybe this would be useful to have this on top of 
the file:

static Rcpp::Argument par("par") ;
static Rcpp::Argument fval("fval") ;
static Rcpp::Argument feval("feval") ;
static Rcpp::Argument minpval("minpval") ;

and then replace :

Rcpp::List rr(Rcpp::Pairlist(Rcpp::Named("par", par),
				 Rcpp::Named("fval",
					     F77_NAME(calfun)(&n,
							      par.begin(),
							      ip.begin())),
				 Rcpp::Named("feval", rho.get(".feval.")),
				 Rcpp::Named("intpval", fval)));


by :

Rcpp::List rr = make_list(
	par  = par_,
	fval = F77_NAME(calfun)(&n, par.begin(), ip.begin()),
	feval = rho.get(".feval."),
	intpval = fval_
	)

(notice the underscore in par_ and fval_ because I use the variable name 
for the Argument instance ... but this is just an example.

Romain


Le 15/03/10 21:26, Romain Francois a ?crit :