Create a two-dimensional array at runtime: Difference between revisions

Content added Content deleted
Line 2,318: Line 2,318:
zkl doesn't have a native array type but lists of lists can do the same thing. It is garbage collected so things are cleaned up implicitly.
zkl doesn't have a native array type but lists of lists can do the same thing. It is garbage collected so things are cleaned up implicitly.


This code creates a 2d row major zero filled array.
This code creates three 2d row major arrays, the only difference is the initial values. In the first case, the columns are initialized to row; the second case all zeros; finally, the column value.


Since the array is row major, sub-scripting works as expected: [row][col].
The fp/fpM methods are function/partial application, which saves using a lambda. M mean mask, in this case fixing the first one or two parameters and chopping any after that (both pumps try to add a value parameter, one or the other or neither is used).

Since the array is row major, sub-scripting works as expected: [row][col]. [row,length] is the other option.

The pump method creates read only lists, ROList.copy() returns a writable list. You can achieve this other ways but this is simple. The reason for "copy" is, again, to save a lambda. Pump takes a list of actions, a string action means do late binding and run the result. The list of rows is left read only.
<lang zkl>rows:=ask("Rows: ").toInt();
<lang zkl>rows:=ask("Rows: ").toInt();
cols:=ask("columns: ").toInt();
cols:=ask("columns: ").toInt();
rows.pump(List,cols.pump.fp(List),"copy") .println();
array:=rows.pump(List.createLong(rows),List.createLong(cols,0).copy);
array[1][2]=123;
/*-->*/ rows.pump(List,cols.pump.fpM("11-",List,0),"copy") .println(); // you usually want this
(array:= rows.pump(List,cols.pump.fpM("1-",List),"copy")) .println();
array.println();
array[1][2].println();
array[1][2].println();</lang>
The createLong method pre-allocates a list, optionally filled with a constant or computation.
array[1,2].println(); // probably not what you want</lang>
{{out}}
<pre>
Rows: 3
columns: 4
L(L(0,0,0,0),L(0,0,123,0),L(0,0,0,0))
123
</pre>
If you want Matrix/linear algebra, you can use the GNU Scientific Library:
<lang zkl>var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
rows:=ask("Rows: ").toInt();
cols:=ask("columns: ").toInt();
m:=GSL.Matrix(rows,cols);
m[1,2]=3;
m.format().println();
println(m[1,2]);</lang>
Again, garbage collected.
{{out}}
{{out}}
<pre>
<pre>
Rows: 3
Rows: 3
columns: 4
columns: 4
0.00, 0.00, 0.00, 0.00
L(L(0,0,0,0),L(1,1,1,1),L(2,2,2,2))
0.00, 0.00, 3.00, 0.00
L(L(0,0,0,0),L(0,0,0,0),L(0,0,0,0))
0.00, 0.00, 0.00, 0.00
L(L(0,1,2,3),L(0,1,2,3),L(0,1,2,3))
3
2
L(L(0,1,2,3),L(0,1,2,3))
</pre>
</pre>