The goal is to have the user input (for the sake of argument) a linear function in one variable, for example 2*x+3 along with the variable (this isn't crucial) and a value for the variable. I would then like to calculate the value of the function. The following works, but I'm thinking now that it works more by accident than anything else.
My original attempt
\findvalueBfailed and didn't seem to like the underscore, so I tried the method of\findvalueAwhich worked. Why does one of these work and the other not?When deciding to switch variable names to test, I ran into the obvious problems (e.g. using
ybreaks\mytoks. So I tried to hardcode a variable name, again failure. The basic idea seems to work as shown at the bottom. Why does this try fail?
Presumably there's a common thread to what I'm not getting and it's likely a fundamental misunderstanding of something that I'd like to correct. I'm more interested in the explanation than a code solution although both would be nice.
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\newtoks\mytoks
\NewDocumentCommand {\findvalueA} { m m m }
{
\group_begin:
\char_set_catcode_active:N #1
\tl_rescan:nn{}{\def#1{#2}}
\tl_rescan:nn{}{\mytoks={#3}}
\fp_set:Nn \l_tmpa_fp {\the\mytoks}
\fp_use:N \l_tmpa_fp
\group_end:
}
\NewDocumentCommand {\findvalueB} { m m m }
{
\group_begin:
\char_set_catcode_active:N #1
\tl_rescan:nn{}{\def#1{#2}}
% underscores=bad
\tl_rescan:nn{}{\tl_set:Nn \l_tmpa_tl {#3}}
% or
% \tl_rescan:nn{}{\fp_eval:n {#3}}
\fp_use:N \l_tmpa_fp
\group_end:
}
\NewDocumentCommand {\findvalueC} { m m }
{
\group_begin:
\char_set_catcode_active:N x
\tl_rescan:nn {} {\defx{#1}}
\tl_rescan:nn {} {\mytoks={#2}}
\fp_set:Nn \l_tmpa_fp {\the\mytoks}
\fp_use:N \l_tmpa_fp
\group_end:
}
\ExplSyntaxOff
\begin{document}
% works
\findvalueA{x}{5}{2*x+3}
% fails
%\findvalueB{x}{5}{2*x+3}
% fails
%\findvalueC{5}{x+2}
The method of findvalueC works down here but not above: if $x=5$, then $x+2=$
\ExplSyntaxOn
\group_begin:
\char_set_catcode_active:N x
\defx{5}
\fp_eval:n {x+2}
\group_end:
\ExplSyntaxOff
\end{document}