0
$\begingroup$

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

Input:

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

G[n^2]

Output:

(n+1)^2

$\endgroup$
  • 1
    $\begingroup$ My math must be slipping: how did you get from $n^2$ to $(n+1)^2$? $\endgroup$ – J. M. will be back soon Jun 9 '16 at 5:17
  • 1
    $\begingroup$ It should return a function or just an expression like above? $\endgroup$ – Kuba Jun 9 '16 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 Jun 10 '16 at 1:43
2
$\begingroup$

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]

Then

g[n^2, n]

(1 + n)^2

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

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

but

g[a + Sqr[x], y]

$Failed

$\endgroup$

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.