【问题标题】:using "apply()" with methods that return void in specman使用“apply()”和在 specman 中返回 void 的方法
【发布时间】:2009-07-02 18:09:56
【问题描述】:

Specman 有 apply() 方法对列表的所有元素执行相同的操作:

var a: list of int;
a = somefunction.that.returns.list.of.int();
var b:= a.apply(it * 2);

apply() 的作用与以下相同:

for each in a {
    b.add(it.*2);
};

现在,如果我想在a 的元素上调用一个方法,我可以使用apply(),只要该方法返回一个值。但是,如果我有:

struct bar {
    x: int;

    foo() is {
       message(LOW, "x is ", x); 
    };
};

我尝试这样做:

var a: list of bar;
a = somefunction.that.returns.list.of.bar();
a.apply(it.foo());

它无法编译,因为foo() 返回void。相反,我必须使用显式循环:

for each in a {
    it.foo();
};

specman 中是否有类似于apply() 的不需要返回值的方法?

【问题讨论】:

    标签: list specman


    【解决方案1】:

    我认为这里的基本问题是你想误用apply()。我想说这个函数有一些函数式编程背景,它的目的是对列表的每个项目做一些事情并返回一个列表(比如Python中的map或Perl)。

    如果您对函数调用的副作用感兴趣,如果函数不返回值,那么使用显式循环会更正确。另见Is there a value in using map() vs for?

    这表示我目前想不出其他解决方案。也许将 foo() 包装在一个返回值的函数中,但这绝对看起来超载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      • 2018-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多