# Module returns multiple functions

I want to write a module that returns two functions which then can be evaluated later on. I know how to do it with a single function, but I don't know how to make it work for multiple functions.

An example for the single function case:

prep[p1_, p2_] := Module[{},
f1[x_, y_] := (p1 + p2)*x + y;
f1[#1, #2] &
];
myfunc = prep[1, 2];
myfunc[1, 3]


For this input myfunc returns 6 as expected. Now what I would like to have is not a single function returned but multiple (for example two). I have tried to do the following

prep[p1_, p2_] := Module[{},
f1[x_, y_] := (p1 + p2)*x + y;
f2[x_, y_] := (p1 - p2)*x - y;
{f1[#1, #2],f2[#3,#4]} &
];
{myfunc1,myfunc2} = prep[1, 2];


but I get an error saying that the two lists are different (which is somewhat understandable).

Is there a simple way to return multiple functions in a similar way?

• Try myDoubleFunc = prep[1, 2]; myDoubleFunc[1, 2, 3, 4]. This will return a list of two elements, each one being the result of evaluation of f1 and f2, respectively. May 12, 2022 at 16:16
• Isn't there a way to assign them individually? May 12, 2022 at 16:17
• Sure, but you need to change the definition inside the module. Change the return value to {f1, f2} inside Module, then call it as {myFunc1, myFunc2} = prep[1, 2]; and then you can use them independently. May 12, 2022 at 16:20
• @MarcoB Thank you, now it works. Can you explain the difference between returning myFunc[#] and simply myFunc ? May 12, 2022 at 16:30

The correct syntax is:

prep[p1_, p2_] := Module[{},
f1[x_, y_] := (p1 + p2)*x + y;
f2[x_, y_] := (p1 - p2)*x - y;
{f1, f2}];


Then:

{myfunc1, myfunc2} = prep[1, 2];


And e.g.:

myfunc1[10, 20]
myfunc2[10, 20]

(*50,-30*)

prep[p1_, p2_] := Module[{}, f1[x_, y_] := (p1 + p2)*x + y;
f2[x_, y_] := (p1 - p2)*x - y;
{f1[#1, #2] &, f2[#1, #2] &}];
{myfunc1, myfunc2} = prep[1, 2];
myfunc1[1, 2]
myfunc2[1, 2]


I would forgo the whole Module thing:

prep[p1_, p2_] :=
{Function[{x, y}, (p1 + p2)*x + y], Function[{x, y}, (p1 - p2)*x - y]}


Then:

prep[a, b][[1]][x, y]
(* (a+b) x+y *)


and

{f1, f2} = prep[a, b]
(* {Function[{x$$,y$$},(a+b) x$$+y$$],Function[{x$$,y$$},(a-b) x$$-y$$]} *)

f1[x, y]
(* (a+b) x+y *)


This way you don't litter your session with stray DownValues for f1,f2.

I'm a bit concerned that in your original attempt you used #1,#2,#3,and #4, which suggests that you actually want prep to return a function of four inputs (which in turn returns a list of two values when evaluated). If that's the case, then the answer would be different.

• How should I change this prep function if I not only want to return the list of functions, but also carry out some other calculations? May 12, 2022 at 18:53
• I'm sure there are myriad ways to do that. It would help to know what other calculations you want to do. If they're not relevant to this question, post a different one. May 12, 2022 at 19:02