Function projections in R


#1

Hello, I am looking at a way to reproduce so called function projections in APL like langages.
Say I define a function
my_fun <- function(x,y,z,t)
{
//
}
A projection would be to define another function of 3 or less variables, with my_fun. For instance my_fun(1,y,"black",t) would be a function of two variables.
Of course I know I can define it explicitly,but is there a package that would allow me to do something like
lapply(1:10, FUN=my_fun(1,4,"black",.))


#2

I'm not familiar with the the term "function projection", but from your example it looks like purrr::partial will be a good fit in this case.


#3

Can you give me an example not sure how using another function can add syntactic sugar here.
thanks


#4

For example, this can be achieved with:

new_fun <- purrr::partial(my_fun, x = 1, z = "black")

new_fun will be a function of 2 arguments (y and t) that you can use in lapply or wherever.


#5

If you just want to use it in lapply without creating a new function, you can provide the "static" arguments:

lapply(1:10, FUN = my_fun, x = 1, y = 4, z = "black")

Then it will feed each of the numbers in 1:10 to the function as the first unspecified argument (in this case, t).


#6

OK, thing is that it does not looks much handier than doing
proj <- function(y,t) { return(my_fun(1,y,"black",t))}

What I expected was also to be able to chain, for instance monoadic_fun = my_fun(1,.,"black",t)(1,.)


#7

Thank you, but this was just as an example.


#8

Using magrittr with purrr, you can chain.

library(purrr)
library(magrittr)

my_fun <- function(x, y, z, t) {
    list(x = x, y = y, z = z, t = t)
}

monoadic_fun <- my_fun %>%
  partial(x = 1, z = "black") %>%
  partial(y = 1)

monoadic_fun(9)
# $`x`
# [1] 1
# 
# $y
# [1] 1
# 
# $z
# [1] "black"
# 
# $t
# [1] 9

#9

Ah OK that's close!
It is a bit long to write but will do the trick.
Would there be any syntactic sugar that would allow to do this using () (I guess I can define my own operator to remove the need of writing partial all the time)


#10

With R, nearly everything's possible, including this. But hammering R into another language's shape isn't a good idea. If you prefer writing and reading code in another language, why not use it? Even if the project is mostly R, you can write scripts in another language and call them using the system2() function.


#11

Well yes, you can say this about most languages. I also totally disagree about not trying to adapt convinient things from other langages, especially when it comes to functional programing.
But I do not really want to enter this discussion. Thanks for showing the pipe + partial way, by defining an operator I get something much better than redefining the function