String or Other Type

Answer could be a string or another data type

Complete Code

Download file: StringOrOtherType.pg

PG problem file

Explanation

DOCUMENT();

loadMacros('PGstandard.pl', 'PGML.pl', 'PGcourse.pl');

Preamble

These standard macros need to be loaded.
$y = random(0, 4);

if ($y < 4) {
    $answer = String('none')->cmp(typeMatch => Formula('x'));
} else {
    $answer = Formula('2x');
}

Setup

There are several predefined strings, such as NONE, DNE, INF, and INFINITY. If another string is needed it will need to be added to the context. See Adding Strings to a Context.

When $answer = Formula('2x') and a student enters the string NONE, there will not be an error message. This is because MathObject formula answers are set up to accept string answers that are defined in the context. However, when $answer = String('none') and a student enters the formula 2x, they will get an error message. This is because string answers do not also accept formulas. So use typeMatch => Formula('x') so that in this case no error message will appear.

It is recommended that you do not use the technique demonstrated in this sample problem anymore. Instead use the method demonstrated in Answers with Alternate Forms. That method is more intuitive for students, and does not lead to an invalid statement for the answer such as y = NONE.

BEGIN_PGML
Is there a line through the points [`(0, 0)`], [`(1, 2)`], and [`(2, [$y])`]?
If there is, enter the equation for this line.  If not, enter _NONE_.

[`y =`] [_]{$answer}{15}
END_PGML

Statement

This is the problem statement in PGML.
BEGIN_PGML_SOLUTION
Solution explanation goes here.
END_PGML_SOLUTION

ENDDOCUMENT();

Solution

A solution should be provided here.