[R] Partial function application in R

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Fri Jan 16 08:46:47 CET 2009


czesc,

looks like you want some sort of currying, or maybe partial currying,
right?  anyway, here's a quick guess at how you can modify your bind,
and it seems to work, as far as i get your intentions,  with the plot
example you gave:

bind = function(f, ...) {
   args = list(...)
   function(...) do.call(f, c(list(...), args)) }

plotlines = bind(plot, type='l')
plotlines(1:10, runif(10))

plotredlines = bind(plotlines, col="red")
plotredlines(runif(10))

# careful about not overriding a named argument
plotredpoints = bind(plotredlines, type="p")
plotredpoints(runif(10))

you may want to figure out how to get rid of the smart y-axis title.
is this what you wanted?

pzdr,
vQ


nosek wrote:
> Well, 
>
> it looks like it's a perfectly correct approach to bind functions writing
> their wrappers by hand.
> But I don't want to write them by hand every time I need them.
> Being lambda expression, function() is most general, but there must be some
> kind of shorter way for such a common task as partial application.
>
>
> David Winsemius wrote:
>   
>> How is function() not the correct approach?
>>
>>  > plot_lines <- function(x, ...) plot(x,  type="l", ...)
>>  >
>>  > plot_lines(1:10, xlim = c(1,5))
>>
>>  > plot_lines(1:10, 11:20, xlim = c(1,5))
>>
>> Still seems to get the unnamed optional y argument to the plotting  
>> machinery.
>>
>> -- 
>> David Winsemius
>>
>> On Jan 15, 2009, at 4:25 PM, nosek wrote:
>>
>>     
>>> Hello,
>>>
>>> in a desperate desire of using partial function application in R I  
>>> fried out
>>> the following piece of code:
>>>
>>> bind <- function( f, ... ) {
>>>  args <- list(...)
>>>  function(...) f( ..., unlist(args) )
>>> }
>>>
>>> Its purpose, if not clear, is to return a function with part of its
>>> arguments bound to specific values, so that I can for example create  
>>> and use
>>> functions like this:
>>> q1 <- bind( quantile, 0.25 )
>>> lapply( some_list, q1 )
>>>
>>> It's been a lot of work and unfortunately is not perfect. My bind  
>>> applies
>>> arguments only using positional rule. What I dream of is a function  
>>> bind2
>>> that would apply keyword arguments, like:
>>> plot_lines <- bind2( plot, type="l" )
>>> which would return
>>> function(...) plot( type="l", ... )
>>>
>>> How to do this in R?
>>>
>>> Regards,
>>>




More information about the R-help mailing list