如何在Rascal中的列表上编写递归函数? 我希望以下类似的东西可以工作,但它并没有
list[int] inc([]) = [];
list[int] inc([int H, *int T]) = [H+1,inc(T)];
答案 0 :(得分:3)
如果你想用这种风格写它,这将有效:
list[int] inc([]) = [];
list[int] inc([int H, *int T]) = [H+1, *inc(T)];
请注意*
递归调用前面的inc
,这表示将结果拼接回列表 - 需要因为inc
本身返回一个列表。另一种方法是编写第二个函数,如下所示,它使用+
进行列表连接:
list[int] inc([int H, *int T]) = (H+1) + inc(T);
在Rascal中写一个更标准的方法是使用列表理解,如:
list[int] inc(list[int] xs) = [ x + 1 | x <- xs ];
List
库还包含一个名为mapper
的函数,它允许您通过列表映射函数;使用它,您可以将其写为:
mapper(xs, int(int x) { return x + 1; });
其中xs
是整数列表。