Documentation:WeBWorK/Problem Authoring Templates/Numeric from list

From UBC Wiki
Jump to: navigation, search


Your problem has a correct answer that is a scalar entered by the student into a text field, but there may be more than one correct value, any of which is acceptable.


There are two parts to your code:

  1. In the problem set-up section, create a List of Real MathObjects with the correct values and assign it to a known variable. E.g, $meaning_of_life = List(Real(0), Real(42));.
  2. In the answer section, call the ANS command with the correct value's cmp method, giving it a custom list answer checker that will give full points if the student's answer is any of the acceptable values. The custom checker in this case receives as arguments a reference to the list of correct values, reference to the student's answer (also a list, even if containing zero or one elements), and a reference to the AnswerHash, a data structure of additional information about the answer checker and the student's answer (see the MAA wiki for the full details). Your checker needs to iterate through the list of correct values, compare each one to the student's answer, and award the full points (i.e., the score of length equal to the number of acceptable answers) if any of them match, or zero otherwise. For example:
ANS($meaning_of_life->cmp(list_checker => sub {
   my ($correct, $student, $ansHash) = @_;
   my $score = 0;
   my @errors; # stores error messages
   if (scalar(@{$student} == 1)) {
      my $answer = ${$student}[0];

      # iterate through correct values and compare them to
      # the student's answer
      foreach my $value (@{$correct}) {
         # this uses the currently active tolerance value 
         # (e.g., as set for the context or the specific Real MathObject)
         if (($value <=> $answer) == 0) {
            # WebWork interprets "score" as the number of correct
            # values in the student's answer. In this case, getting
            # one value correct should be treated as getting all of
            # them correct:
            $score = scalar(@{$correct});
      # if we get to here and the score is still 0, the
      # student's answer didn't match any of the correct values
      if ($score == 0 && ! $ansHash->{isPreview}) {
         push @errors, "Not correct";
   elsif (! $ansHash->{isPreview}) {
      push @errors, "You have to enter a single number";
   return ($score, @errors);

See the MAA wiki for details.

Source code

Please download the following attachment to access the code in a single file. Unfortunately, the Wiki restricts filename extensions, so that it couldn't end in ".pg", which is what WebWork expects. You can rename it after downloading, or simply copy-and-paste its contents into the standard WebWork browser-based problem editor.

Template file source.