# Wolfram modules returning functions

I am trying to get a With / Module pair to return a set of functions.

Funky[n_] := With[{x = n},
Module[{LocalFunc1, LocalFunc2, MkLocalFunc},
LocalFunc1[y_] := x + y;
LocalFunc2[y_] := x - y;
MkLocalFunc[_fnToUse] := With[{UseLocalFunc = fnToUse},
Module[{LocalFunc},
LocalFunc[w_] = UseLocalFunc[w] + 10;
LocalFunc
]
];
{MkLocalFunc[LocalFunc1], MkLocalFunc[LocalFunc2]}
]
]
(Funky[1] // First)[1]


Here I expected the output to be 12 but it returns MkLocalFunc$636015[LocalFunc1$636015][1] Why won't it evaluate MkLocalFunc\$636015?

• What is the intent of this function? Jan 10, 2021 at 14:45
• @J.M.'sennui. My guess is that it is for self-education. Jan 10, 2021 at 14:46
• The MkLocalFunc[_fnToUse] part is a little odd; this basically restricts MkLocalFunc[] to only evaluate on anything with an fnToUse head. I wonder if MkLocalFunc[fnToUse_] was intended instead, considering the With[] that follows... Jan 10, 2021 at 14:48

Simplifying a bit and fixing a typo:

Funky[n_] := Module[{LocalFunc1, LocalFunc2, MkLocalFunc},
LocalFunc1[y_] = n + y;
LocalFunc2[y_] = n - y;
MkLocalFunc[fnToUse_] := Module[{LocalFunc},
LocalFunc[w_] = fnToUse[w] + 10;
LocalFunc];
{MkLocalFunc[LocalFunc1], MkLocalFunc[LocalFunc2]}]

(Funky[1] // First)[1]
(*    12    *)


The only typo that mattered was the one @J.M. pointed out: replace _fnToUse by fnToUse_.

Note that the With clauses are superfluous and clutter the code.

In Mathematic this sort thing is much more easily done with Function Like so:

Funky[n_] := {(n + # + 10) &, (n - # + 10) &}
{f, g} = Funky[1]


{1 + #1 + 10 &, 1 - #1 + 10 &}

Then

f[1]

12

g[1]

10


Now let's look at what (1 + # + 10) & means.

(n + # + 10) & // FullForm

Function[Plus[1, Slot[1], 10]]


where Slot[1] is a descriptor for the 1st argument and we see that Function is indeed what the Mathematica evaluator sees.

Sometimes it is useful or even needful to skip the keyboard shortcuts & and #, and in such cases one can and should dispense with Slot and use symbols to indicate its argument(s). An example is a function that takes an integer as its argument and returns a function accepting a list and returning all elements in the list that are to right of the specified integer index.

h = Function[i, Part[#, i + 1 ;;] &];
h[3][Range[6]]

{4, 5, 6}