# Using rule output as function

Im trying to define a function using the output from RSolve, however i cant get it to work properly.

I have a RSolve that output something like:

BK[n] -> 2n + 5


and now i would like to define a function that has that property like:

BK[n_] := 2n + 5


so that when i do for instance:

BK[4]


i'll get 13. Is there a way to use this rule and define it as a function as proposed above? Note that the rule is far more complicated than what i gave as an example so that's why i dont want to simply copy the output as it is.

• What you are asking can be done. But the better solution would be to RSolve for BK instead of BK[n], because that would give you a pure function which can be used directly. – Shredderroy Feb 5 at 20:19
• Right... and never use upper-case letters for your functions, as they might conflict with the internal functions of Mathematica. – David G. Stork Feb 5 at 20:26

You can use RSolveValue[eqn,a,n] the result of which is a pure function that can be used as is without any further processing:

ClearAll[bK]
bK = RSolveValue[a[n + 1] - 2 a[n] == 1, a, n];
bK[2]


3 + 2 C[1]

Update: For multiple functions:

ClearAll[bk, ff, if]
eq1 = bk[n + 1] == 0.9 bk[n] + 0.25 ff[n] + 0.2 if[n];
eq2 = ff[n + 1] == 0.05 bk[n] + 0.7 ff[n] + 0.2 if[n];
eq3 = if[n + 1] == 0.05 bk[n] + 0.05 ff[n] + 0.6 if[n];
{bkF, ffF, ifF} = RSolveValue[{eq1, eq2, eq3, bk[0] == 2000, ff[0] == 1000,
if[0] == 2000}, {bk, ff, if}, n];

bkF[2]


2775.

ffF[3]


1200.

ifF[5]


628.252

• Great! Thanks alot! :) – Oscar Johansson Feb 5 at 21:50

I agree with others that for your ultimate goal, you should consider other use cases of RSolveValue.. But I wanted to, for fun, add an answer to the question "use rule to define function", and I wonder if anybody else has any nifty answers to this as well.. Here's one I came up with:

In[6]:=

setRuleDelayed[Rule[lhs_, rhs_]] :=
Quiet[
(Evaluate[Replace[lhs, (val_ :> val_), {1}]] := rhs)
,
RuleDelayed::rhs
]
setRuleDelayed[BK[n] -> 2 n + 5]
DownValues[BK]

Out[8]= {HoldPattern[BK[n_]] :> 5 + 2 n}

In[9]:= BK[4]

Out[9]= 13


RSolveValue seems to be working for just one function however this is the case:

eq1 = bk[n+1] == 0.9 bk[n] + 0.25 ff[n] + 0.2 if[n];
eq2 = ff[n+1] == 0.05 bk[n] + 0.7 ff[n] + 0.2 if[n];
eq3 = if[n+1] == 0.05 bk[n] + 0.05 ff[n] + 0.6 if[n];
sol= RSolve[{eq1,eq2,eq3,bk[0] == 2000,ff[0] == 1000,if[0] == 2000 },{bk[n],ff[n],if[n]},n] //First //FullSimplify


To clarify; I would like each separate functions (bk,ff,if) to be defined as function that I can use. i.e bk[2] = something, ff[3] = something else

Thanks for the help!

• Oscar, please see the update in my answer. – kglr Feb 5 at 21:46