3
$\begingroup$

Let's say that you have a function with symbols, i.e.

f[x] = x^2 +a[1] 

I want to define a new function

g[x,a[1]] = x^2 +a[1]
$\endgroup$
1
  • $\begingroup$ f returning a[1] is fraught with potential problems. If a is defined before a call to f then you will get unexpected behavior. $\endgroup$
    – Edmund
    Apr 12 at 1:20

1 Answer 1

2
$\begingroup$

f returning a[1] is fraught with potential problems. If a is defined before a call to f then you will get unexpected behavior.

fBadIdea[x_] := x^2 + a[1]

Then

fBadIdea[2]
4 + a[1]

This seems fine. However, you have a problem with

a = {1, 2};
fBadIdea[2]
4 + {1, 2}[1]

It is best practice to return Formal Symbols for non-scoped symbols; see docs for keyboard shortcuts.

enter image description here

f[x_] := x^2 + \[FormalA][1]

Now

f[2]

enter image description here

4 + \[FormalA][1]

but any attempt to assign to \[FormalA] is blocked so you don't get unexpected results.

enter image description here

For g

g[x_, a_] := f[x] /. \[FormalA][1] -> a

and

g[2, c]
4 + c

as required.

Hope this helps.

$\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.