WeBWorK Problems

Showing correct answers as expressions in PG

Showing correct answers as expressions in PG

by Yuncong Chen -
Number of replies: 3
I was trying this code in PG:

$a = 2;
$b = Compute("1+$a");

In the Hint, I expect it to display $b as "1+2", so I used Compute for $b. Then in the hint section I just wrote:
\($b\)

but what is displayed is the value 3.

Could you tell me why Compute does not produce the desired effect of an expression? Thanks.

In reply to Yuncong Chen

Re: Showing correct answers as expressions in PG

by John Travis -
Set up this way:

$a = 2;
$b = "1+$a";

Then:

Enter b:  \{ans_rule(10)\}

Use answer checker:

ANS( str_cmp($b));

JT

In reply to Yuncong Chen

Re: Showing correct answers as expressions in PG

by Alex Jordan -
Compute works the way you are expecting when it is creating a Formula object. As you are entering it, Compute sees a Real and it simplifies.

This will achieve what you are trying to do, by forcing the expression to be parsed as a Formula, and setting the flag that stops arithmetic reduction in Formulas:

Context("Numeric");
Context()->flags->set(reduceConstants=>0);

$a = 2;
$b = Formula("1+$a");

In reply to Yuncong Chen

Re: Showing correct answers as expressions in PG

by Davide Cervone -
As Alex points out, the value of $b is a Real, and when $b is inserted into a string (like the text of the hint), it's value is inserted. The original string is saved to be used as the correct answer string, but that is the only place the original string is used.

Alex suggests setting reduceConstants=>0 and using Formula rather than Compute to get the effect you want. That is a good suggestion provided you are not using $b as an answer that the student must enter. If you make $b a formula, then ANS($b->cmp) will make an answer checker that expects the student to enter a formula (not a number) and will produce error messages to that effect, which could be misleading.

There are two solutions to this. Either use ANS($b->eval->cmp) if you use $b as an answer, or use
$b=Compute("1+$a") and \($b->{original_formula}\) instead (along with the reduceConstants=>0 flag).

Hope that helps.

Davide