# How to define a function which takes another function as input in Module

Let $f$ be a function of $n$. I would like to define a function $A$ with module which takes $f[n]$ as input. So for example:

f[n_]:=f[n]=(n^2+1)/n;
A[f[n]_]:=A[f[n]]=Module[{d},
d[n_]=d[n]=Numerator[f[n-1]];
Return[d[n]]
]


My code above does not work. I want f[n] still be a function of n inside the module but it seems I did it wrong. Any help is appreciated.

• Instead of a function defined with a pattern like f[n_], you can try f = Function[n, (n^2 + 1)/n]. Then pass both f and n to A: A[f_Function, n_] := ... – Marius Ladegård Meyer Jun 15 '16 at 6:08
• @MariusLadegårdMeyer. I think I cannot do that because actually f is another output from another function. But thanks for the answer :D – Chen M Ling Jun 15 '16 at 8:32

Do you mean:

ClearAll[A]
Attributes@A = HoldAll;
A[f[n_]] := A[f[n]] = Module[{d}, d = Numerator@f[n - 1]]


I've removed the redundant Return. Module is also irrelevant here actually. Anyway, I suppose you need Module in your real problem so don't take it away.

Or you need f to be arbitrary, too? Then:

ClearAll[A]
Attributes@A = HoldAll;
A[f_[n_]] := A[f[n]] = Module[{d}, d = Numerator@f[n - 1]]

f[n_] := f[n] = (n^2 + 1)/n;
g[n_] := g[n] = (n^2 + 2)/n;

A[g]
(* 3 *)
A[f]
(* 5 *)

A // DownValues
(* {HoldPattern[A[f]] :> 5, HoldPattern[A[g]] :> 3,
HoldPattern[A[f_[n_]]] :> (A[f[n]] = Module[{d}, d = Numerator[f[n - 1]]])} *)

• +1 for the nice examples, but if interpretation is correct, and I think it is, this should probably be closed as a duplicate. – Mr.Wizard Jun 15 '16 at 6:36
• @Mr.Wizard Yeah, I believe it's a duplicate, too, but posts about functions are really hard to search 囧. Hope someone can find the duplicate post. – xzczd Jun 15 '16 at 6:40
• Oh. This works! But when I removed Attributes@A = HoldAll; it did not work. What is that for? – Chen M Ling Jun 15 '16 at 8:30
• Oh when I make $d$ a function in $n$ too, it doeas not work. A[f_[n_]] := A[f[n]] = Module[{d}, d[n_]:=d[n] = Numerator@f[n - 1]] doesn't work. Sorry, I do not know how to format a code in a comment. – Chen M Ling Jun 15 '16 at 8:48
• @ChenMLing To understand the meaning of Attributes@A = HoldAll;, just check the document of Attributes and HoldAll, you may also feel this post interesting. As to the d[n] part, I don't quite understand what you mean. What output are you expecting? – xzczd Jun 15 '16 at 10:37