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:


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.

  • 1
    $\begingroup$ 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_] := ... $\endgroup$ – Marius Ladegård Meyer Jun 15 '16 at 6:08
  • $\begingroup$ @MariusLadegårdMeyer. I think I cannot do that because actually f is another output from another function. But thanks for the answer :D $\endgroup$ – Chen M Ling Jun 15 '16 at 8:32

Do you mean:

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:

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;

(* 3 *)
(* 5 *)

A // DownValues
(* {HoldPattern[A[f[3]]] :> 5, HoldPattern[A[g[3]]] :> 3, 
    HoldPattern[A[f_[n_]]] :> (A[f[n]] = Module[{d}, d = Numerator[f[n - 1]]])} *)
  • $\begingroup$ +1 for the nice examples, but if interpretation is correct, and I think it is, this should probably be closed as a duplicate. $\endgroup$ – Mr.Wizard Jun 15 '16 at 6:36
  • 1
    $\begingroup$ @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. $\endgroup$ – xzczd Jun 15 '16 at 6:40
  • $\begingroup$ Oh. This works! But when I removed Attributes@A = HoldAll; it did not work. What is that for? $\endgroup$ – Chen M Ling Jun 15 '16 at 8:30
  • $\begingroup$ 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. $\endgroup$ – Chen M Ling Jun 15 '16 at 8:48
  • $\begingroup$ @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? $\endgroup$ – xzczd Jun 15 '16 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.