WeBWorK Problems

Variables in strings

Re: Variables in strings

by Davide Cervone -
Number of replies: 0
As you have found out, this is really not the way to go about this. Even had you succeeded in defining your values as strings in the context, no other hex numbers would be there, so any other hex value would produce error messages.

The technical reason why your string "17A" didn't work while "A65" did is because the various object types each have a priority, and it turns out that numbers are before strings (by default, though that can be changed), so the "17" in "17A" matched as a number, leaving the "A" as the next thing to parse (thus the error about A not being defined), while "A65" didn't match as a number, but eventually did as a string.

Your approach of using str_cmp() does work, in the sense that it will mark the correct answer correct, and incorrect answers as incorrect, but it will not report syntax errors, or type errors, or any of the other helpful things that MathObject will do for you. Also, you won't be able to enter expressions in hex (in case you were interested in that).

The better approach would be to make a context in which hexadecimal numbers were recognized. I was going to give you a basic layout for that, but got carried away and did the full thing myself. See the attached contextHex.pl file. To use it just set Context("Hex"), and then use $n = Compute('17A') or $n = Compute('A65'). From there, you use $n as a MathObject as usual (e.g., ANS($n->cmp)).

Note that this context included definitions for bitwise operators &, |, ^, >>, <<, and ~ (for "and", "or", "exclusive or", "shift right", "shift left" and "not"). You cause them in student answers, inside Compute() or in your PG code directly, (e.g., $m = $n & 0xFF).

Finally, to convert a perl integer to a hex MathObejct, use Hex(), as in $n = Hex(123) to convert the (decimal) number 123 into the equivalent of Compute('7B'). You can also use $n = Hex(0x7B) to do the same thing.

If you don't want to allow students to be able to perform computations within their answers, use Context("LimitedHex"), which disables all the operators (other than unary minus and commas for lists).

I hope that does what you need.