Package jmathexpr.arithmetic.pattern

Source Code of jmathexpr.arithmetic.pattern.FractionPattern

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package jmathexpr.arithmetic.pattern;

import jmathexpr.Expression;
import jmathexpr.arithmetic.natural.NaturalNumber;
import jmathexpr.arithmetic.op.Division;
import jmathexpr.arithmetic.op.Multiplication;
import jmathexpr.arithmetic.rational.RationalNumber;
import jmathexpr.util.pattern.AbstractPattern;
import jmathexpr.util.pattern.AnyPattern;

/**
* Pattern for a fraction a/b.
*
* @author Elemér Furka
*/
public class FractionPattern extends AbstractPattern {
   
    private final AnyPattern numerator = new AnyPattern();
    private final AnyPattern denominator = new AnyPattern();
   
    @Override
    public boolean matches(Expression expr) {
        if (expr instanceof RationalNumber) {
            NaturalNumber d = ((RationalNumber) expr).denominator();
           
            return !d.isOne() && numerator.matches(((RationalNumber) expr).numerator())
                    && denominator.matches(d);
        } else if (expr instanceof Division) {
            return numerator.matches(((Division) expr).lhs())
                    && denominator.matches(((Division) expr).rhs());
        } else if (expr instanceof Multiplication) {
            Multiplication m = (Multiplication) expr;
           
            if (matches(m.lhs())) { // a/b * c -> ac/b
                return numerator.matches(new Multiplication(numerator.hit(), m.rhs()));
            } else if (matches(m.rhs())) { // a * b/c -> ab/c
                return numerator.matches(new Multiplication(m.lhs(), numerator.hit()));
            }
        }
       
        return false;
    }
   
    /**
     * Returns the numerator after a successful match.
     *
     * @return the matching fraction's numerator
     */
    public Expression numerator() {
        return numerator.hit();
    }
   
    /**
     * Returns the denominator after a successful match.
     *
     * @return the matching fraction's denominator
     */
    public Expression denominator() {
        return denominator.hit();
    }
}
TOP

Related Classes of jmathexpr.arithmetic.pattern.FractionPattern

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.