From closure to a function of several variables

Let's assume I have the closure

F <- function(a, b) {
  function(x) {
    a*x^b
  }
}

and I want to create a sum G of F-functions

G(x, y, z) = F_1(x) + F_2(y) + F_3(z)

that depends on several variables (not just x). However, F_2 should not depend on x for example.

For start, I would use a function that adds together a list of functions:

addFunctions <- function(x, l) {
  # x variable
  # l list of functions
  sum(sapply(l, function(f) f(x)))
}

I start by defining the F-functions and

F_1 <- F(1, 2)
F_2 <- F(3, 4)
F_3 <- F(4, 5)
G <- function(x) {addFunctions(x, list(F_1, F_2, F_3))}

However, this would only give me a function G of one variable x.

Why wouldn't I just define the sum directly? Well, because the case I really have is much more complicated and the number of independent variables may vary.

Any suggestions?

Is this an acceptable solution ?

F <- function(a, b) {
  function(x) {
    a*x^b
  }
}

F_1 <- F(1, 2)
F_2 <- F(3, 4)
F_3 <- F(4, 5)

library(purrr)

addfuncs <- function(xlist,flist){
  sum(map2_dbl(.x = xlist,
       .y = flist,
      .f = ~.y(.x)))
}

addfuncs(c(1,2,3),list(F_1,F_2,F_3))
addfuncs(c(3,2,1),list(F_1,F_2,F_3))
1 Like

Thank you, that is extremely helpful!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.