Skip to content

[Rcpp-devel] sugar: ifelse, pmin, pmax, lapply

1 message · Romain Francois

#
Hi,

I've implemented lazy versions of them in Rcpp::sugar.

Here are some examples:

fx <- cxxfunction( signature( x = "integer" ), '
	IntegerVector xx(x) ;
	List res = lapply( xx, seq_len );
	return res ;	
', plugin = "Rcpp" )
checkEquals( fx( 1:10 ), lapply( 1:10, seq_len ) )



fx <- cxxfunction( signature( x = "numeric" ), '
		NumericVector xx(x) ;
		return List::create(
			pmin( xx, 5),
			pmin( 5, xx)
			) ;
	', plugin = "Rcpp" )
	
checkEquals( fx(1:10) ,
	list(
		c(1:5,rep(5,5)),
		c(1:5,rep(5,5))
	)
)


fx <- cxxfunction( signature( x = "numeric", y = "numeric" ), '
	NumericVector xx(x) ;
	NumericVector yy(y) ;
	
	NumericVector res = ifelse( xx < yy, xx*xx, -(yy*yy) ) ;
	return res ;
', plugin = "Rcpp" )

x <- 1:10
y <- 10:1
checkEquals( fx( x, y), ifelse( x<y, x*x, -(y*y) ) )


One thing to notice about ifelse is that it only evaluates either the 
rhs or the lhs, given the condition. This differs from R which has to 
evaluate both.

Romain