【问题标题】:Check if indexed variable has a value assigned somewhere检查索引变量是否在某处分配了值
【发布时间】:2021-10-15 07:59:32
【问题描述】:

第 1 部分

如果我们有这个

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

然后

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

但是

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

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

所以 Maple 确实有足够的关于变量 a 及其索引的信息。我们如何在不打印的情况下检查这些信息?

对于小型索引这不是问题,但是如果 b[123457891234578912345789]:=789; 那么我们如何检查是否有某个索引 ib[i] 定义了值以及该索引 i 是什么(不打印,即不是手动)?

第 2 部分

我希望能够在函数中使用此类变量并返回此类变量。 例如,假设我想将所有索引增加 1。如果我知道存在哪些索引,那么我可以这样做

[> 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

但我通常不知道 a 有什么索引变量。

【问题讨论】:

    标签: maple indexed


    【解决方案1】:

    您可以进行多种程序化查询,

    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 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]
    

    【讨论】:

    • 非常感谢! type(a, table);[indices(a, 'nolist')];这两个命令就可以解决问题了!
    • 但是变量可以同时具有两种不同的类型仍然很奇怪,因为type(a, symbol);type(a, table);都返回true。这不是bug吗?
    • type(a,symbol) 返回true(即使a 被分配了table)的原因是所谓的姓氏评估。旧的table 数据结构获得了“lne”以允许某些功能,例如。当作为 proc 参数传递时,就地行为作为可变结构。 lne 的一些描述:maplesoft.com/support/help/maple/view.aspx?path=last_name_eval
    • 谢谢,该链接还解释了 eval 的用法。所以我可以使用whattype(eval(a)) 来检查最终类型并使用op(eval(a)) 来提取索引(在需要键=值格式时特别有用)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 2019-10-03
    相关资源
    最近更新 更多