Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.
f[x2_] = ToExpression[StringTake[ToString[x2], -1]] x2;
f[a3]
(*Out: 2 a3*)

I expected the output to be 3 a3, but apparently x2 isn't evaluated in ToString.

How would one construct a function that gives the expected result?

share|improve this question
4  
Use SetDelayed[] instead of Set[]. –  J. M. Oct 10 '12 at 13:29
add comment

1 Answer 1

up vote 5 down vote accepted

You have to use SetDelayed to get the desired behaviour. If you use only set, then to ToString just sees x2, which is where the two is coming from.

So this gives the correct result:

f[x2_] := ToExpression[StringTake[ToString[x2], -1]] x2;
f[a3]
(* 3 a3*)

Have a look at this tutorial on Set and SetDelayed.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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