## WeBWorK Main Forum

### combining contexts (piecewise functions and fractions)

by Michael Shulman -
Number of replies: 4
I find it confusing how certain things in webwork are implemented as Contexts that I would expect to simply be objects. In particular, my understanding is that only one Context can be active at a time, so what do I do if I want to use more than one of those things?

At the moment I am particularly interested in piecewise functions and fractions, each of which is apparently enabled by setting a Context. I want to define a piecewise function that includes fractions (without converting them to decimals); how do I do it?

### Re: combining contexts (piecewise functions and fractions)

by Alex Jordan -
The Fraction context is more for:
• enforcing that students enter fraction answers using fractions, not decimals. This is with respect to actual fraction answers, not expressions which happen to have fractions in them.
• a shortcut to make sure that any fraction you generate is automatically reduced.

If what you want to do is create a Formula in some other context where things like "1/2 x" do not display as "0.5x", then you can set the flag which stops arithmetic simplification in formulas:

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

Then Formula("1/2 x") will display as "\frac{1}{2}x". (Also Formula("2/4 x") will display as "\frac{2}{4}x and Formula("4/2 x") will display as "\frac{4}{2}x.)

If you additionally want a Formula answer where you force students to enter their answers using fractions, then I think you need to use bizarroArithmetic.pl. Or maybe LimitedRadical.pl would enough.

### Re: combining contexts (piecewise functions and fractions)

by Michael Shulman -
Ideally, what I want is for

Formula("1/2 x") to display as "\frac{1}{2}x".
Formula("2/4 x") to display as "\frac{1}{2}x".
Formula("4/2 x") will display as "2x".

Is that possible?

### Re: combining contexts (piecewise functions and fractions)

by Michael Shulman -
I think I figured it out: I set Context("Fraction") and define the pieces of the piecewise function individually, then set Context("PiecewiseFunction") and define the function using a hash of intervals, so that the pieces that were defined in fraction context aren't stringified and re-parsed, and thereby remain fractions.
But back to those three examples. If I am in a situation where I need to use Formula("$a/$b x"), then along with turning off the reduceConstants flag, I also use the Fraction context to make $frac=Fraction($a,$b), and then make Formula("$frac x"). This will leave each of the three cases that you gave displaying as you want.