GTM>for i=1:1:5 write i,! 1 2 3 4 5The above
for loop a variable i from 1 to 5, increasing by 1 in each iteration.
This one will loop over a list of arguments
GTM>for i="hello","world","bye","moon" write i,! hello world bye moonarray
In M array is stored as sparse B-tree structure, index or subscript can be anything and can be in any number
GTM> GTM>set a(1)="hello",a(2)="world" GTM>write a(1)," ",a(2) hello world GTM> GTM>write a(3) %GTM-E-UNDEF, Undefined local variable: a(3)the index of an Array can be any thing so it is like hash/dictionary in other language.
GTM>set a("hello")=1
GTM>set a("world")=2
GTM>write a("hello")
1
GTM>write a("world")
2
GTM>write a("moon")
%GTM-E-UNDEF, Undefined local variable: a(moon)
We can use any number of subscripts
GTM>set a(1,2)="moon" GTM>set a(1,1)="world" GTM>write a(1,1) world GTM>write a(1,2) moon GTM>write a(1,0) %GTM-E-UNDEF, Undefined local variable: a(1,0)built-in function
$order is used to get index/subscript of an element of an Array, that is particularly useful for traversal over an Array.
GTM>set b(3)="hello",b(5)="world",b("hello")=1,b("world")=2
GTM>write $order(b("")); with empty string we get a subscript of the first element of an Array
3
GTM>write $order(b(3)); passing one element we get a subscript of next element
5
GTM>write $order(b(5))
hello
GTM>write $order(b("hello"))
world
GTM>write $order(b("world")); passing the last element we get empty string
If array is multi dimensional, $order will return subscript of an element in one dimension
GTM>set a("h",1)="hello",a("w",1)="world"
GTM>write $order(a("")); return subscript in the first dimension of first element
h
GTM>write $order(a("h")); return subscript in the first dimension of second element
w
GTM>write $order(a("w"))
GTM>write $order(a("h","")); return subscript in the second dimension of first element
1
GTM>write $order(a("h",1))
GTM>write $order(a("w","")); return subscript in the second dimension of second element
1
GTM>write $order(a("w",1))
traversal over a array
for is typical command used to traversal an array
GTM>kill a for i=1:1:10 set a(i)=i*iWe use
kill to erase content of the variable a if exists and a for to create 10 elements.
GTM>set i="" for set i=$order(a(i)) quit:i="" write i," ",a(i),!; two SPACE after for and two SPACE after quit:i="" 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100Here, the argument-less For repeats until stopped by a terminating quit. This line prints a table of i and a(i)
block of multi line of codes under for
M support execute multi line of code under for in the routine
GTM>zedit "nested" finish for name="ivan","john","janes" do . if name]"jo"; the operator ] test if name follows string "jo" . else write name,! quit GTM>zlink "nested" GTM>do finish^nested ivan janes GTM>
No comments:
Post a Comment