欣快感 - 序列


序列由大括号 { } 中的对象列表表示,并用逗号分隔。序列可以包含Atomics和其他序列。例如 -

{2, 3, 5, 7, 11, 13, 17, 19}
{1, 2, {3, 3, 3}, 4, {5, {6}}}
{{"Zara", "Ayan"}, 52389, 97.25}
{} -- the 0-element sequence

可以通过在方括号中给出元素编号来选择序列的单个元素。元素编号从 1 开始。

例如,如果 x 包含 {5, 7.2, 9, 0.5, 13},则 x[2] 为 7.2。

假设 x[2] 包含 {11,22,33},现在如果你要求 x[2],你会得到 {11,22,33},如果你要求 x[2][3],你会得到Atomics 33 。

例子

#!/home/euphoria-4.0b2/bin/eui

sequence x
x = {1, 2, 3, 4}

for a = 1 to length(x) do
   printf(1, "value of x[%d] = %d\n", {a, x[a]})
end for

这里,length() 是返回序列长度的内置函数。上面的例子产生以下结果 -

value of x[1] = 1
value of x[2] = 2
value of x[3] = 3
value of x[4] = 4

字符串

字符串只是一个字符序列。可以通过两种方式之一输入 -

(a) 使用双引号 -

"ABCDEFG"

(b) 使用原始字符串表示法 -

-- Using back-quotes
`ABCDEFG`

or

-- Using three double-quotes
"""ABCDEFG"""

您可以尝试以下示例来理解这个概念 -

#!/home/euphoria-4.0b2/bin/eui

sequence x
x = "ABCD"

for a = 1 to length(x) do
   printf(1, "value of x[%d] = %s\n", {a, x[a]})
end for

这会产生以下结果 -

value of x[1] = A
value of x[2] = B
value of x[3] = C
value of x[4] = D

字符串数组

可以使用序列实现字符串数组,如下所示 -

#!/home/euphoria-4.0b2/bin/eui

sequence x = {"Hello", "World", "Euphoria", "", "Last One"}

for a = 1 to length(x) do
   printf(1, "value of x[%d] = %s\n", {a, x[a]})
end for

这会产生以下结果 -

value of x[1] = Hello
value of x[2] = World
value of x[3] = Euphoria
value of x[4] =
value of x[5] = Last One

欣快感结构

可以使用序列来实现结构,如下所示 -

#!/home/euphoria-4.0b2/bin/eui

sequence employee = {
   {"John","Smith"},
      45000,
      27,
      185.5
}
printf(1, "First Name = %s, Last Name = %s\n", {employee[1][1],employee[1][2]} )

这会产生以下结果 -

First Name = John, Last Name = Smith

有多种可以直接对序列执行的操作。让我们详细看看它们 -

泌尿手术

当应用于序列时,一元运算符实际上应用于序列中的每个元素,以产生相同长度的结果序列。

#!/home/euphoria-4.0b2/bin/eui

sequence x
x = -{1, 2, 3, 4}

for a = 1 to length(x) do
   printf(1, "value of x[%d] = %d\n", {a, x[a]})
end for

这会产生以下结果 -

value of x[1] = -1
value of x[2] = -2
value of x[3] = -3
value of x[4] = -4

算术运算

几乎所有算术运算都可以在序列上执行,如下所示 -

#!/home/euphoria-4.0b2/bin/eui

sequence x, y, a, b, c
x = {1, 2, 3}
y = {10, 20, 30}

a = x + y
puts(1, "Value of a = {")

for i = 1 to length(a) do
   printf(1, "%d,", a[i])
end for
puts(1, "}\n")

b = x - y
puts(1, "Value of b = {")
for i = 1 to length(a) do
   printf(1, "%d,", b[i])
end for
puts(1, "}\n")

c = x * 3
puts(1, "Value of c = {")

for i = 1 to length(c) do
   printf(1, "%d,", c[i])
end for
puts(1, "}\n")

这会产生以下结果 -

Value of a = {11,22,33,}
Value of b = {-9,-18,-27,}
Value of c = {3,6,9,}

命令行选项

用户可以将命令行选项传递给 Euphoria 脚本,并且可以使用command_line()函数将其作为序列进行访问,如下所示 -

#!/home/euphoria-4.0b2/bin/eui

sequence x

x = command_line()

printf(1, "Interpeter Name: %s\n", {x[1]} )
printf(1, "Script Name: %s\n", {x[2]} )
printf(1, "First Argument: %s\n", {x[3]})
printf(1, "Second Argument: %s\n", {x[4]})

这里printf()是 Euphoria 的内置函数。现在,如果您按如下方式运行此脚本 -

$eui test.ex "one" "two"

这会产生以下结果 -

Interpeter Name: /home/euphoria-4.0b2/bin/eui
Script Name: test.ex
First Argument: one
Second Argument: two