Search code examples
mapleindexed

Check if indexed variable has a value assigned somewhere


Part 1

If we have this

[> restart; a[5]:=23: a[7]:=41:

then

[> about(a); whattype(a);
a:
  nothing known about this object
                        symbol

but

[> print(a);
                 table([5 = 23, 7 = 41])

and

[> convert(a,list);
                        [23, 41]

So Maple does have enough information about variable a and its indexes somewhere. How can we check that information without printing?

For small indexes it's not a problem, but if b[123457891234578912345789]:=789; then how do we check if there is some index i for which b[i] has a defined value and what that index i is (without printing, i. e. not manually)?

Part 2

I'd like to be able to work with such variables inside a function and return such variable. For example, let's say I want to increase all indexes by 1. If I know which indexes exist then I can do that

[> a[5]:=23: a[7]:=41:
   f:=proc(x) local y;
      y[6]:=x[5]; y[8]:=x[7]; y;
      end proc:
   b:=f(a); b[6]; b[8];
           b:=y
            23
            41

but often I don't know what indexes variable a has.


Solution

  • There are several programmatic queries you can make,

    restart;
    a[5]:=23: a[7]:=41:
    
    # test whether a is assigned
    assigned('a');
                      true
    
    # test whether a is assigned a table
    type(a, table);
                      true
    
    # test whether table a has any indexed values
    evalb( nops([indices(a, 'nolist')]) > 0 );
    
                      true
    
    assigned('a'[7]);
                      true
    

    If you wish you can make such queries prior to attempting to access and utilize the indexed reference (ie. to check that it has an assigned value). For example,

    if type(a,table) and assigned('a'[7]) then
      a[7];
    end if;
                 41
    
    if type(a, table) then
      [indices(a, 'nolist')];
    end if;
                [5, 7]