########################################################## # # Example showing how to add new operators to the Parser # DOCUMENT(); # This should be the first executable line in the problem. loadMacros( "PGbasicmacros.pl", "PGanswermacros.pl", "Parser.pl", "parserTables.pl", ); TEXT(beginproblem()); ########################################################## # # Define our own binary operator # package MyOperator; our @ISA = qw(Parser::BOP); # subclass of Binary OPerator # # Check that the operand types are numbers. # sub _check { my $self = shift; my $name = $self->{bop}; return if $self->checkNumbers(); $self->Error("Operands of '$name' must be Numbers"); } # # Compute the value of n choose r. # sub _eval { shift; my ($n,$r) = @_; my $C = 1; $r = $n-$r if ($r > $n-$r); # find the smaller of the two for (1..$r) {$C = $C*($n-$_+1)/$_} return $C } # # Non-standard TeX output # sub TeX { my $self = shift; return '{'.$self->{lop}->TeX.' \choose '.$self->{rop}->TeX.'}'; } # # Non-standard perl output # sub perl { my $self = shift; return '(MyOperator->_eval('.$self->{lop}->perl.','.$self->{rop}->perl.'))'; } package main; ########################################################## # # Add the operator into the current context # $prec = Context()->operators->get('+')->{precedence} - .25; Context()->operators->add( '#' => { class => 'MyOperator', precedence => $prec, # just below addition associativity => 'left', # computed left to right type => 'bin', # binary operator string => ' # ', # output string for it TeX => '\mathop{\#}', # TeX version (overridden above, but just an example) } ); $CHOOSE = MODES(TeX => '\#', HTML => '#'); ########################################################### # # The problem text # BEGIN_TEXT $BEGIN_ONE_COLUMN In this problem, we have added a new operator to the Parser: ${BTT}n $CHOOSE r${ETT}, which returns \(n\choose r\). $PAR \{ParserTable( 'Formula("x # y")', 'Formula("x+1 # 5")', 'Formula("x # 5")->eval(x=>7)', 'Formula("(x#5)+(x#4)")', 'Formula("x#5+x#4")', 'Formula("x # y")', 'Formula("x # y")->substitute(x=>5)', 'Formula("x # y")->eval(x=>5,y=>2)', 'Formula("x # y")->perlFunction(~~'C~~'); C(5,2)', 'Formula("1 # ")', )\} $END_ONE_COLUMN END_TEXT ########################################################### ENDDOCUMENT(); # This should be the last executable line in the problem.