在 Julia 中访问集合的每个元素 – foreach() 方法
foreach()
是 julia 中的内置函数,用于在指定的可迭代 c 的每个元素上调用函数f。
Syntax: foreach(f, c…)
Parameters:
- f: Specified set of instructions.
- c: Specified iterable.
Returns: It returns the result of the operation of function f on each element of the specified iterable c.
示例 1:
# Julia program to illustrate
# the use of foreach() method
# Getting the result of the operation
# of function f on each element of
# the specified array a.
a = [1, 2, 3];
foreach(x -> println(x ^ 3), a)
输出:
1
8
27
示例 2:
# Julia program to illustrate
# the use of foreach() method
# Getting the result of the operation
# of function f on each element of
# the specified iterable c.
a = 1:3;
foreach(x -> println(x ^ 2), a)
输出:
1
4
9