I want to write a function via a module that takes a user's input and creates a function from the input within the module.

That is something like


G[nterm_] := 
  Module[{n, r},
    r[n_] := nterm




  • 1
    $\begingroup$ My math must be slipping: how did you get from $n^2$ to $(n+1)^2$? $\endgroup$ Commented Jun 9, 2016 at 5:17
  • 1
    $\begingroup$ It should return a function or just an expression like above? $\endgroup$
    – Kuba
    Commented Jun 9, 2016 at 6:32
  • $\begingroup$ Thanks for the quick response, please let me put in in context.. I'm implementing Gosper's algorithm (page 87 of A=B: math.upenn.edu/~wilf), so it needs to take a hypergeometric term as input and convert it to a rational function (or expression?) r(n) = t(n+1)/t(n) then execute a series of loops etc. The problems arise in the loops where the function definition is updated throughout. Simply defining a function f[n_]:=blah and trying to update it's definition in a loop doesn't seem to work. It seems replacement rules using /.-> might offer the solution.. not sure though? $\endgroup$
    – MathMuppt
    Commented Jun 10, 2016 at 1:43

1 Answer 1


I don't see any reason to use Module for what you seem to asking. I suggest

g[expr_, var_Symbol] := If[FreeQ[expr, var], $Failed, expr /. var -> var + 1]


g[n^2, n]

(1 + n)^2

g[2 Sqrt[x] + y^x, x]

2 Sqrt[1 + x] + y^(1 + x)


g[a + Sqr[x], y]



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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