Macaulay2 » Documentation
Packages » Macaulay2Doc » The Macaulay2 language » installing methods » installing augmented assignment methods
next | previous | forward | backward | up | index | toc

# installing augmented assignment methods

In most cases, the default behavior of augmented assignment gives the desired result. But in some situations, it may be useful to override this behavior and install a custom method for a given type.

Consider the following example.

    i1 : Foo = new SelfInitializingType of MutableList;

    i2 : net Foo := x -> net x#0;

    i3 : Foo + Foo := (x, y) -> Foo {x#0 + y#0};

    i4 : x = Foo {1}

    o4 = 1

    o4 : Foo

    i5 : y = Foo {2}

    o5 = 2

    o5 : Foo

    i6 : x += y

    o6 = 3

    o6 : Foo

Note that an intermediate `Foo` object was created and then assigned to `x`. Instead, it would be more efficient if `x` was modified directly.

    i7 : installMethod(symbol +=, Foo, (x, y) -> (x#0 += y#0; x));

    i8 : x += y

    o8 = 5

    o8 : Foo

In some cases, it may be useful to fall back on the default behavior of the given operator. When this is desired, the installed method should return the Default symbol.

    i9 : Bar = new SelfInitializingType of List;

    i10 : net Bar := x -> net x#0#0;

    i11 : Bar * Bar := (x, y) -> Bar {{x#0#0 * y#0#0}};

    i12 : installMethod(symbol *=, Bar, (x, y) -> if isMutable x#0 then (
                  print "using custom method";
                  x#0#0 *= y#0#0; x) else Default)

    o12 = FunctionClosure[stdio:12:30-14:39]

    o12 : FunctionClosure

    i13 : x = Bar {new MutableList from {3}}

    o13 = 3

    o13 : Bar

    i14 : y = Bar {{4}}

    o14 = 4

    o14 : Bar

    i15 : x *= y
    using custom method

    o15 = 12

    o15 : Bar

    i16 : y *= x

    o16 = 48

    o16 : Bar

## See also

- augmented assignment
- installing methods

The source of this document is in /build/macaulay2-88fgJW/macaulay2-1.25.11+ds/M2/Macaulay2/packages/Macaulay2Doc/operators/augmented_assignment.m2:83:0.