Search in sources :

Example 1 with ReturnException

use of org.matheclipse.core.eval.exception.ReturnException in project symja_android_library by axkr.

the class PatternMatcher method evalAST.

/**
	 * 
	 * @param lhsPatternAST
	 * @param lhsEvalAST
	 * @param rhsExpr
	 * @param stackMatcher
	 * @return <code>F.NIL</code> if no match was found.
	 */
protected IExpr evalAST(final IAST lhsPatternAST, final IAST lhsEvalAST, final IExpr rhsExpr) {
    if (lhsPatternAST.size() < lhsEvalAST.size()) {
        if (lhsPatternAST.isOrderlessAST() && lhsPatternAST.isFlatAST()) {
            if (!matchExpr(lhsPatternAST.head(), lhsEvalAST.head(), null)) {
                return F.NIL;
            }
            final OrderlessMatcher foMatcher = new OrderlessMatcher(lhsPatternAST, lhsEvalAST);
            boolean matched = foMatcher.matchOrderlessAST(1, null);
            if (matched) {
                IAST lhsResultAST = (lhsEvalAST).clone();
                foMatcher.filterResult(lhsResultAST);
                IExpr result = fPatternMap.substituteSymbols(rhsExpr);
                try {
                    result = F.eval(result);
                    lhsResultAST.append(result);
                    return lhsResultAST;
                } catch (final ConditionException e) {
                    logConditionFalse(lhsEvalAST, lhsPatternAST, rhsExpr);
                // fall through
                } catch (final ReturnException e) {
                    lhsResultAST.append(e.getValue());
                    return lhsResultAST;
                }
            }
            return F.NIL;
        }
        if (lhsPatternAST.isFlatAST()) {
            if (!matchExpr(lhsPatternAST.head(), lhsEvalAST.head(), null)) {
                return F.NIL;
            }
            int len = lhsEvalAST.size() - lhsPatternAST.size();
            for (int i = 0; i < len; i++) {
                if (matchASTSequence(lhsPatternAST, lhsEvalAST, i, null)) {
                    IAST lhsResultAST = (lhsEvalAST).clone();
                    for (int j = 1; j < lhsPatternAST.size(); j++) {
                        lhsResultAST.remove(i + 1);
                    }
                    try {
                        IExpr result = fPatternMap.substituteSymbols(rhsExpr);
                        result = F.eval(result);
                        lhsResultAST.append(i + 1, result);
                        return lhsResultAST;
                    } catch (final ConditionException e) {
                        logConditionFalse(lhsEvalAST, lhsPatternAST, rhsExpr);
                    } catch (final ReturnException e) {
                        lhsResultAST.append(i + 1, e.getValue());
                        return lhsResultAST;
                    }
                    return F.NIL;
                }
            }
        }
    }
    return F.NIL;
}
Also used : ConditionException(org.matheclipse.core.eval.exception.ConditionException) IAST(org.matheclipse.core.interfaces.IAST) IExpr(org.matheclipse.core.interfaces.IExpr) ReturnException(org.matheclipse.core.eval.exception.ReturnException)

Example 2 with ReturnException

use of org.matheclipse.core.eval.exception.ReturnException in project symja_android_library by axkr.

the class Primality method moebiusMu.

public static int moebiusMu(BigInteger value) {
    if (value.compareTo(BigInteger.ZERO) < 0) {
        value = value.negate();
    }
    if (value.equals(BigInteger.ZERO)) {
        return 0;
    }
    if (value.equals(BigInteger.ONE)) {
        return 1;
    }
    SortedMultiset<BigInteger> map = new SquareFreeTreedMap();
    try {
        Config.PRIME_FACTORS.factorInteger(value, map);
        // value is square-free
        Integer max = 1;
        for (Map.Entry<BigInteger, Integer> entry : map.entrySet()) {
            Integer c = entry.getValue();
            if (c.compareTo(max) > 0) {
                return 0;
            }
        }
        if ((map.size() & 0x00000001) == 0x00000001) {
            // odd number
            return -1;
        }
        return 1;
    } catch (ReturnException re) {
    // not square-free
    }
    return 0;
}
Also used : IInteger(org.matheclipse.core.interfaces.IInteger) BigInteger(java.math.BigInteger) PrimeInteger(edu.jas.arith.PrimeInteger) BigInteger(java.math.BigInteger) Int2IntMap(it.unimi.dsi.fastutil.ints.Int2IntMap) Map(java.util.Map) OpenIntToIExprHashMap(org.matheclipse.core.eval.util.OpenIntToIExprHashMap) Int2IntRBTreeMap(it.unimi.dsi.fastutil.ints.Int2IntRBTreeMap) SortedMap(java.util.SortedMap) ReturnException(org.matheclipse.core.eval.exception.ReturnException)

Example 3 with ReturnException

use of org.matheclipse.core.eval.exception.ReturnException in project symja_android_library by axkr.

the class PatternMatcher method matchFlatSequenceFromIndex.

/**
 * Match two {@link ISymbol#FLAT} <code>ASTs</code> where the <code>lhsEvalFlatAST</code> sequence
 * length can be greater equal than the <code>lhsPatternFlatAST</code> sequence length.
 *
 * <p>
 * Example:
 *
 * <pre>
 * >> SetAttributes(fl, Flat)
 *
 * >> fl(fl(a, b), c)", //
 * fl(a,b,c)
 *
 * >> fl(x_, x_) := fl(x)
 *
 * >> fl(b, b, b, c, c)
 * fl(b,c)
 *
 * >> fl(a, a, a, b, b, b, c, c)
 * fl(a,b,c)
 * </pre>
 *
 * @param lhsPatternFlatAST
 * @param lhsEvalFlatAST
 * @param rhsExpr
 * @param engine
 * @return
 */
private IExpr matchFlatSequenceFromIndex(final IAST lhsPatternFlatAST, final IAST lhsEvalFlatAST, final IExpr rhsExpr, EvalEngine engine) {
    final int len = lhsEvalFlatAST.size() - lhsPatternFlatAST.size() + 1;
    for (int i = 0; i < len; i++) {
        if (matchASTSequence(lhsPatternFlatAST, lhsEvalFlatAST, i, engine, new StackMatcher(engine))) {
            IASTAppendable lhsResultAST = lhsEvalFlatAST.copyAppendable();
            for (int j = 1; j < lhsPatternFlatAST.size(); j++) {
                lhsResultAST.remove(i + 1);
            }
            try {
                IExpr result = fPatternMap.substituteSymbols(rhsExpr, F.CEmptySequence);
                result = engine.evaluate(result);
                lhsResultAST.append(i + 1, result);
                return lhsResultAST;
            } catch (final ConditionException e) {
                if (LOGGER.isDebugEnabled()) {
                    logConditionFalse(lhsEvalFlatAST, lhsPatternFlatAST, rhsExpr);
                }
            } catch (final ReturnException e) {
                lhsResultAST.append(i + 1, e.getValue());
                return lhsResultAST;
            }
            return F.NIL;
        }
    }
    return F.NIL;
}
Also used : ConditionException(org.matheclipse.core.eval.exception.ConditionException) IASTAppendable(org.matheclipse.core.interfaces.IASTAppendable) IExpr(org.matheclipse.core.interfaces.IExpr) ReturnException(org.matheclipse.core.eval.exception.ReturnException)

Example 4 with ReturnException

use of org.matheclipse.core.eval.exception.ReturnException in project symja_android_library by axkr.

the class ExprEvaluator method evalTryCatch.

public static IExpr evalTryCatch(final IExpr expr, EvalEngine[] engineRef) {
    EvalEngine engine = engineRef[0];
    EvalEngine.set(engine);
    // engine.reset() must be done before parsing step
    IExpr preRead = S.$PreRead.assignedValue();
    IExpr temp;
    try {
        if (preRead != null && preRead.isPresent()) {
            temp = engine.evaluate(F.unaryAST1(preRead, expr));
        } else {
            temp = engine.evaluate(expr);
        }
    } catch (ReturnException rex) {
        LOGGER.debug("ExprEvaluator.evalTryCatch() failed", rex);
        return rex.getValue();
    } catch (BreakException | ContinueException conex) {
        LOGGER.debug("ExprEvaluator.evalTryCatch() failed", conex);
        IAST ast = F.Continue();
        if (conex instanceof BreakException) {
            ast = F.Break();
        }
        // No enclosing For, While or Do found for `1`.
        IOFunctions.printMessage(S.Continue, "nofwd", F.list(ast), engine);
        temp = F.Hold(ast);
    } catch (ThrowException e) {
        LOGGER.debug("ExprEvaluator.evalTryCatch() failed", e);
        // Uncaught `1` returned to top level.
        IAST ast = F.Throw(e.getValue());
        IOFunctions.printMessage(S.Throw, "nocatch", F.list(ast), engine);
        temp = F.Hold(ast);
    } catch (IterationLimitExceeded e) {
        LOGGER.debug("ExprEvaluator.evalTryCatch() failed", e);
        // Iteration limit of `1` exceeded.
        int iterationLimit = engine.getIterationLimit();
        IOFunctions.printMessage(S.$IterationLimit, "itlim", F.list(iterationLimit < 0 ? F.CInfinity : F.ZZ(iterationLimit), expr), engine);
        temp = F.Hold(expr);
    } catch (RecursionLimitExceeded e) {
        LOGGER.debug("ExprEvaluator.evalTryCatch() failed", e);
        // Recursion depth of `1` exceeded during evaluation of `2`.
        int recursionLimit = engine.getRecursionLimit();
        IOFunctions.printMessage(S.$RecursionLimit, "reclim2", F.list(recursionLimit < 0 ? F.CInfinity : F.ZZ(recursionLimit), expr), engine);
        temp = F.Hold(expr);
    }
    if (!engine.isOutListDisabled()) {
        engine.addInOut(expr, temp);
    }
    return temp;
}
Also used : RecursionLimitExceeded(org.matheclipse.core.eval.exception.RecursionLimitExceeded) ThrowException(org.matheclipse.core.eval.exception.ThrowException) ContinueException(org.matheclipse.core.eval.exception.ContinueException) BreakException(org.matheclipse.core.eval.exception.BreakException) IExpr(org.matheclipse.core.interfaces.IExpr) IAST(org.matheclipse.core.interfaces.IAST) IterationLimitExceeded(org.matheclipse.core.eval.exception.IterationLimitExceeded) ReturnException(org.matheclipse.core.eval.exception.ReturnException)

Example 5 with ReturnException

use of org.matheclipse.core.eval.exception.ReturnException in project symja_android_library by axkr.

the class PatternMatcherAndEvaluator method checkRHSCondition.

/**
 * Check if the condition for the right-hand-sides <code>Module[], With[] or Condition[]</code>
 * expressions evaluates to <code>true</code>.
 *
 * @return <code>true</code> if the right-hand-sides condition is fulfilled or not all patterns
 *         are assigned.
 */
@Override
public boolean checkRHSCondition(EvalEngine engine) {
    IPatternMap patternMap = createPatternMap();
    if (patternMap.getRHSEvaluated()) {
        return true;
    }
    if (!(fRightHandSide.isCondition() || fRightHandSide.isModuleOrWithCondition())) {
        return true;
    } else {
        if (!patternMap.isAllPatternsAssigned()) {
            return true;
        } else {
            boolean matched = false;
            IExpr rhs = patternMap.substituteSymbols(fRightHandSide, F.CEmptySequence);
            engine.pushOptionsStack();
            IEvalStepListener stepListener = engine.getStepListener();
            try {
                engine.setOptionsPattern(fLhsPatternExpr.topHead(), patternMap);
                if (Config.TRACE_REWRITE_RULE && stepListener != null) {
                    IExpr lhs = getLHSExprToMatch();
                    if (lhs.isPresent()) {
                        stepListener.setUp(lhs, 0);
                        fReturnResult = engine.addEvaluatedTraceStep(lhs, rhs, lhs.topHead(), F.$str("RewriteRule"));
                    } else {
                        fReturnResult = engine.evaluate(rhs);
                    }
                } else {
                    fReturnResult = engine.evaluate(rhs);
                }
                matched = true;
            } catch (final ConditionException e) {
                matched = false;
            } catch (final ReturnException e) {
                fReturnResult = e.getValue();
                matched = true;
            } finally {
                engine.popOptionsStack();
            }
            if (Config.TRACE_REWRITE_RULE && stepListener != null) {
                stepListener.tearDown(0, matched);
            }
            patternMap.setRHSEvaluated(matched);
            return matched;
        }
    }
}
Also used : ConditionException(org.matheclipse.core.eval.exception.ConditionException) IEvalStepListener(org.matheclipse.core.interfaces.IEvalStepListener) IExpr(org.matheclipse.core.interfaces.IExpr) ReturnException(org.matheclipse.core.eval.exception.ReturnException)

Aggregations

ReturnException (org.matheclipse.core.eval.exception.ReturnException)10 IExpr (org.matheclipse.core.interfaces.IExpr)9 ConditionException (org.matheclipse.core.eval.exception.ConditionException)5 IAST (org.matheclipse.core.interfaces.IAST)3 IOException (java.io.IOException)2 AbortException (org.matheclipse.core.eval.exception.AbortException)2 FailedException (org.matheclipse.core.eval.exception.FailedException)2 IASTAppendable (org.matheclipse.core.interfaces.IASTAppendable)2 SyntaxError (org.matheclipse.parser.client.SyntaxError)2 MathException (org.matheclipse.parser.client.math.MathException)2 PrimeInteger (edu.jas.arith.PrimeInteger)1 Int2IntMap (it.unimi.dsi.fastutil.ints.Int2IntMap)1 Int2IntRBTreeMap (it.unimi.dsi.fastutil.ints.Int2IntRBTreeMap)1 BigInteger (java.math.BigInteger)1 Map (java.util.Map)1 SortedMap (java.util.SortedMap)1 BreakException (org.matheclipse.core.eval.exception.BreakException)1 ContinueException (org.matheclipse.core.eval.exception.ContinueException)1 IterationLimitExceeded (org.matheclipse.core.eval.exception.IterationLimitExceeded)1 RecursionLimitExceeded (org.matheclipse.core.eval.exception.RecursionLimitExceeded)1