我需要在 Ballerina 中set使用array字符串创建字符串。除了在插入之前使用reduce()或检查之外indexOf(),我找不到创建set使用 Ballerina 编程语言的方法。
string[] arr = ["a", "b", "c", "a", "d", "c"];
string[] set = arr.reduce(function(string[] accum, string item) returns string[] {
if accum.indexOf(item) == () {
accum.push(item);
}
return accum;
}, []);
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法在 Ballerina 中创建场景?
这并不完全是一个集合,但最近 Ballerina查询表达式有一个group by子句,可用于从数据容器中过滤掉重复项,从而有效地创建容器的“集合”版本。
$ bal version
Ballerina 2201.8.3 (Swan Lake Update 8)
Language specification 2023R1
Update Tool 1.4.2
Run Code Online (Sandbox Code Playgroud)
$ cat uniq.bal
import ballerina/io;
function uniq(anydata[] data) returns anydata[] {
return
from var item in data
group by item
select item;
}
type Data record {|
int x;
int y;
|};
public function main() {
int[] nums = [1,1,2,2,3,3,4,4,5,5];
io:println(uniq(nums));
string[] strs = ["foo","foo","bar","bar","zoo","zoo"];
io:println(uniq(strs));
Data[] data = [{x:0, y:0},{x:0, y:0},{x:1, y:1},{x:1, y:1},{x:2, y:2},{x:2, y:2}];
io:println(uniq(data));
}
Run Code Online (Sandbox Code Playgroud)
打印以下预期结果:
$ bal run uniq.bal
Compiling source
uniq.bal
Running executable
[1,2,3,4,5]
["foo","bar","zoo"]
[{"x":0,"y":0},{"x":1,"y":1},{"x":2,"y":2}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
413 次 |
| 最近记录: |