【问题标题】:Test function for checking an optional argument用于检查可选参数的测试函数
【发布时间】:2019-05-16 05:39:52
【问题描述】:

与我之前的question 相关,我尝试创建一个函数present() 来检查可选参数的存在。但是,下面的代码

proc present( x ) { return x.type != void; }

proc test( a: ?T = _void )
{
    writeln();
    writeln( "test| a = ", a );
    writeln( "test| condition    = ", a.type != void );
    writeln( "test| present( a ) = ", present( a ) );

    if present( a )       // error (Line 1)
    // if a.type != void  // works (Line 2)
    {
        a = 10;
    }
}

// no optional arg
test();

// pass an optional array
var arr: [1..5] int;
test( a = arr );

writeln();
writeln( "main| arr = ", arr );

给出编译时错误

mytest.chpl:3: In function 'test':
mytest.chpl:13: error: illegal lvalue in assignment
mytest.chpl:13: error: a void variable cannot be assigned

这表示a = 10; 行有问题。另一方面,如果我使用第 2 行而不是第 1 行,则代码按预期工作:

test| a = 
test| condition    = false
test| present( a ) = false

test| a = 0 0 0 0 0
test| condition    = true
test| present( a ) = true

main| arr = 10 10 10 10 10 

另外,如果我将第 1 行或第 2 行替换为 if isArray( a ),代码也可以工作。这是否意味着我们需要让编译器明确知道a_void 时未到达a = 10; 行? (换句话说,present() 是否不足以让编译器知道它,因为测试条件“隐藏”在present() 中?)

【问题讨论】:

    标签: chapel optional-arguments


    【解决方案1】:

    这是否意味着我们需要让编译器明确知道 线 a = 10;当 a 为 _void 时未达到? (换句话说,是 present() 不足以让编译器知道它,因为测试 条件是“隐藏”在 present() 中?)

    是的,没错。编译器需要在编译时知道 if 的主体应该仅在参数不为 void 的情况下编译。将x.type != void 检查放入该条件是一个合理的解决方案,但如果您想要一个函数来计算是否应该评估该条件,您可以这样做。只需将present 标记为param 函数——这意味着它返回一个在编译时应该知道的值。这是完整的示例:

    proc present( x ) param { return x.type != void; }
    
    proc test( a: ?T = _void )
    {
        writeln();
        writeln( "test| a = ", a );
        writeln( "test| condition    = ", a.type != void );
        writeln( "test| present( a ) = ", present( a ) );
    
        if present( a )
        {
            a = 10;
        }
    }
    
    // no optional arg
    test();
    
    // pass an optional array
    var arr: [1..5] int;
    test( a = arr );
    
    writeln();
    writeln( "main| arr = ", arr );
    

    如果您想了解更多关于该领域的语言设计,请参阅language specification 的“过程”一章“返回意图”部分中的"The Param Return Intent" 小节。

    【讨论】:

    • 我在各种 Chapel 代码中看到了很多 param(在 Github 上),但我终于明白为什么它对这种用法很重要......(到目前为止,我对 @ 的用法987654329@ 类似于 Fortran 中的parameter(只是为了定义编译时参数)。我将阅读规范 PDF 了解更多详细信息。非常感谢 :)
    猜你喜欢
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    相关资源
    最近更新 更多