75 lines
2.4 KiB
Plaintext
75 lines
2.4 KiB
Plaintext
-- simple one-dimensional arrays:
|
|
sequence s1 = {0.5, 1, 4.7, 9}, -- length(s1) is now 4
|
|
s2 = repeat(0,6), -- s2 is {0,0,0,0,0,0}
|
|
s3 = tagset(5) -- s3 is {1,2,3,4,5}
|
|
|
|
?s1[3] -- displays 4.7 (nb 1-based indexing)
|
|
s1[3] = 0 -- replace that 4.7
|
|
s1 &= {5,6} -- length(s1) is now 6 ({0.5,1,0,9,5,6})
|
|
s1 = s1[2..5] -- length(s1) is now 4 ({1,0,9,5})
|
|
s1[2..3] = {2,3,4} -- length(s1) is now 5 ({1,2,3,4,5})
|
|
s1 = append(s1,6) -- length(s1) is now 6 ({1,2,3,4,5,6})
|
|
s1 = prepend(s1,0) -- length(s1) is now 7 ({0,1,2,3,4,5,6})
|
|
|
|
-- negative subscripts can also be used, counting from the other end, eg
|
|
s2[-2..-1] = {-2,-1} -- s2 is now {0,0,0,0,-2,-1}
|
|
|
|
-- multi dimensional arrays:
|
|
sequence y = {{{1,1},{3,3},{5,5}},
|
|
{{0,0},{0,1},{9,1}},
|
|
{{1,7},{1,1},{2,2}}}
|
|
-- y[2][3][1] is 9
|
|
|
|
y = repeat(repeat(repeat(0,2),3),3)
|
|
-- same structure, but all 0s
|
|
|
|
-- Array of strings:
|
|
sequence s = {"Hello", "World", "Phix", "", "Last One"}
|
|
-- s[3] is "Phix"
|
|
-- s[3][2] is 'h'
|
|
|
|
-- A Structure:
|
|
sequence employee = {{"John","Smith"},
|
|
45000,
|
|
27,
|
|
185.5}
|
|
|
|
-- To simplify access to elements within a structure it is good programming style to define constants that name the various fields, eg:
|
|
constant SALARY = 2
|
|
|
|
-- Array of structures:
|
|
sequence employees = {
|
|
{{"Jane","Adams"}, 47000, 34, 135.5}, -- a[1]
|
|
{{"Bill","Jones"}, 57000, 48, 177.2}, -- a[2]
|
|
-- .... etc.
|
|
}
|
|
-- employees[2][SALARY] is 57000
|
|
|
|
-- A tree can be represented easily, for example after adding "b","c","a" to it you might have:
|
|
sequence tree = {{"b",3,2},
|
|
{"c",0,0},
|
|
{"a",0,0}}
|
|
|
|
-- ie assuming
|
|
constant ROOT=1, VALUE=1, LEFT=2, RIGHT=3 -- then
|
|
-- tree[ROOT][VALUE] is "b"
|
|
-- tree[ROOT][LEFT] is 3, and tree[3] is the "a"
|
|
-- tree[ROOT][RIGHT] is 2, and tree[2] is the "c"
|
|
|
|
-- The operations you might use to build such a tree (tests/loops/etc omitted) could be:
|
|
tree = {}
|
|
tree = append(tree,{"b",0,0})
|
|
tree = append(tree,{"c",0,0})
|
|
tree[1][RIGHT] = length(tree)
|
|
tree = append(tree,{"a",0,0})
|
|
tree[1][LEFT] = length(tree)
|
|
|
|
-- Finally, some tests (recall that we have already output a 4.7):
|
|
?s[3]
|
|
?tree
|
|
?tree[ROOT][VALUE]
|
|
employees = append(employees, employee)
|
|
?employees[3][SALARY]
|
|
?s1
|
|
?s2
|