Julia有一个用于private getRowData(startRow: number, endRow: number): Observable<any[]> {
// This is acting as a service call that will return just the
// data range that you're asking for. In your case, you'd probably
// call your http-based service which would also return an observable
// of your data.
var rowdata = [];
for (var i = startRow; i <= endRow; i++) {
rowdata.push({ one: "hello", two: "world", three: "Item " + i });
}
return Observable.of(rowdata);
}
onGridReady(params: any) {
console.log("onGridReady");
var datasource = {
getRows: (params: IGetRowsParams) => {
this.getRowData(params.startRow, params.endRow)
.subscribe(data => params.successCallback(data));
}
};
params.api.setDatasource(datasource);
}
循环的并行宏,它允许执行以下操作:
for
,由于指定的化简器为s = @sync @parallel vcat for i in 1:9
k = iseven(i) ? i÷2 : 3i+1
k^2
end
,因此我们得到了一个数字数组。
是否可以使用正常的for循环(无需显式初始化并将push!插入数组)来执行类似的操作?
由于我只想减少使用vcat,因此提出此问题的另一种方法是:是否存在整齐的可读多行形式的数组推导?可以像这样扩展到通常的理解语法:
vcat
,但是与 s = [
(k = iseven(i) ? i÷2 : 3i+1;
k^2)
for i in 1:9
]
语法相比,这看起来很混乱并且可读性较差。有更好的方法进行多行理解吗?
答案 0 :(得分:2)
简短的答案是用单行数组理解或map/mapreduce
编写多行函数(或@phg提醒的do-blocks):
s = [
(k = iseven(i) ? i÷2 : 3i+1;
k^2)
for i in 1:9
]
此示例是纯粹的理解,不涉及任何减速器。数组理解通常写在一行中,例如s = [iseven(i) ? i÷2 : 3i+1 |> x->x^2 for i in 1:9]
。正如@phg所建议的,可以将多行函数包含在do-block中:
julia> map(1:9) do x
k = iseven(x) ? x÷2 : 3x+1
k^2
end
但是,在这种情况下,不需要使用vcat
之类的化简器,但是如果上例中f
的输出是矢量:
julia> function f(x)
k = iseven(x) ? x÷2 : 3x+1
[k^2]
end
f (generic function with 1 method)
julia> s = [f(i) for i in 1:9]
9-element Array{Array{Int64,1},1}:
[16]
[1]
[100]
[4]
[256]
[9]
[484]
[16]
[784]
array comprehension将为您提供向量数组。这次您需要改用mapreduce
:
julia> mapreduce(f, vcat, 1:9)
9-element Array{Int64,1}:
16
1
100
4
256
9
484
16
784
答案 1 :(得分:2)
扩展@Gnimuc的答案,我认为mapreduce
加do
-syntax非常好:
julia> mapreduce(vcat, 1:9) do i
k = iseven(i) ? i÷2 : 3i+1
k^2
end
9-element Array{Int64,1}:
16
1
100
4
256
9
484
16
784