1

任意の型のリストをコピーするジェネリック メソッドを書きたいと思います。私のコード:

copy_list(in_list : list of rf_type) : list of rf_type is {
    var out_list : list of rf_type;
    gen out_list keeping { it.size() == in_list.size(); };
    for each (elem) in in_list {
        out_list[index] = elem.unsafe();
    };
    result = out_list;
};

メソッドの呼び出し:

var list_a : list of uint;
gen list_a;
var list_b : list of uint;
list_b = copy_list(list_a);

エラー:

   ERR_GEN_NO_GEN_TYPE: Type 'list of rf_type' is not generateable
(it is not a subtype of any_struct) at line ...
        gen out_list keeping { it.size() == in_list.size(); };

copy_listさらに、以下を使用してメソッドを定義するときにもエラーが発生しlist of untypedます。

Error: 'list_a' is of type 'list of uint', while expecting
type 'list of untyped'.

リストをコピーするための一般的なメソッドを書くのを手伝ってもらえますか? 助けてくれてありがとう

4

2 に答える 2

4

あなたは自分のアプローチを考えすぎていると思います。copy()疑似メソッドを使用する必要があります。

extend sys {
  run() is also {
    var list1 : list of uint = { 1; 2; 3 };
    var list2 := list1;  // shallow copy, list2 points to list1
    var list3 : list of uint = list1.copy();

    list1.add(4);

    print list1, list2, list3;
  };
};

この例を実行すると、 に 4 が含まれていることがわかりますlist2(これは単に への参照list1であるためです。これは、作成時に含まlist3れていた値のみを含む新しいリストであるためlist1です)。

于 2015-03-29T12:43:38.423 に答える
2

疑似メソッド .copy() を使用しない理由はありますか?

var list_a : list of uint;
gen list_a;
var list_b : list of uint;
list_b = list_a.copy();
于 2015-03-29T12:44:37.500 に答える