Replace Pattern Matching

Issue #103 resolved
liamblack created an issue

I can't really tell does the program support Replace, ReplaceAll and ReplaceRepeated?

Basically does it support pattern matching?

Comments (6)

  1. Axel Kramer repo owner

    The program should support ReplaceAll, ReplacePart and ReplaceRepeated.

    For the missing Replace() function I started this commit: https://bitbucket.org/axelclk/symja_android_library/commits/566ac7b8caebe1d718490c787b0129534a1c7da4

    at the moment the "level specification" feature isn't implmented for the Replace() function.

    These are some examples which should work:

    >>> {1 + a, 2 + a, -3 + a} /. (x_ /; x < 0) + a -> p(x)
    {1+a,2+a,p(-3)}
    
    >>> f(a) + f(b) /. f(x_) -> x^2
    a^2+b^2
    
    >>> u(v(w,x,y) /. { x->y, w->y})
    u(v(y,y,y))
    
    >>> u(v(w,x,y) /. x->y)
    u(v(w,y,y))
    
  2. liamblack reporter

    @axelclk I closed the issue as resolved, but how would do you examples in Java?

    I believe this is a purely Java project yes?

  3. Axel Kramer repo owner

    There are methods in the IExpr interface: replaceAll(), replacePart, replaceRepeated()

    public static void main(String[] args) {
            try {
                F.initSymbols(null, null, false);
    
                // expr = a+b+c
                IAST expr = F.Plus(F.a, F.b, F.c);
                // rule1 = b -> 10*d
                IAST rule1 = F.Rule(F.b, F.Times(F.integer(10), F.d));
                IExpr result = expr.replaceAll(rule1);
                if (result != null) {
                    // print: a+10*d+c
                    System.out.println(result.toString());
                }
                IAST listOfRules = F.List();
                listOfRules.add(rule1);
                // rule2 = b -> 10*e
                IAST rule2 = F.Rule(F.c, F.Times(F.integer(10), F.e));
                listOfRules.add(rule2);
    
                result = expr.replaceAll(listOfRules);
                if (result != null) {
                    // print: a+10*d+10*e
                    System.out.println(result.toString());
                }
    
            } catch (SyntaxError e) {
                // catch Symja parser errors here
                System.out.println(e.getMessage());
            } catch (MathException me) {
                // catch Symja math errors here
                System.out.println(me.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
  4. Axel Kramer repo owner
    a- b /. a -> x
    

    is converted to

    ReplaceAll( a- b , a -> x)
    

    see:

    FullForm(Hold(a- b /. a -> x))
    
  5. Log in to comment