-
Notifications
You must be signed in to change notification settings - Fork 1
Using arrays with operations
Some functions, for example statistical functions, take array type inputs. In this case, using an array input works like any other input.
# This outputs 15
sum([1, 2, 3, 4, 5])
However, if an operation doesn't require an input to be an array type, and you provide an array, then the operation will be executed once for each element in the array, and the operation will output an array with all of the results. Non-array inputs will be the same for each execution. This works for all operations, including operators. For example:
# This outputs: [1, 5, 8]
round([1.2, 4.7, 8.3])
# This executes these operations:
# 2 ^ 2
# 3 ^ 2
# 4 ^ 2
# Outputs: [4, 9, 16]
[2, 3, 4] ^ 2
# The first input to element is required to be an array,
# the second input isn't. So, the first input will be the same
# for each iteration, the second input will be iterated over.
# This executes these operations:
# element([2, 4, 6, 8, 10], 1)
# element([2, 4, 6, 8, 10], 3)
# element([2, 4, 6, 8, 10], 5)
# Outputs: [2, 6, 10]
element([2, 4, 6, 8, 10], [1, 3, 5])
If multiple inputs to the operation are arrays (for inputs not required to be arrays), then they must be the same length as each other, as each execution of the operation will step through all arrays simultaneously. Examples:
# This executes these operations:
# 1 * 4
# 2 * 5
# 3 * 6
# Outputs [4, 10, 18]
[1, 2, 3] * [4, 5, 6]
# Throws error
[1, 2, 3] * [4, 5]
Using conditional operators on an array will return an array of booleans. For example:
a = [1 .. 5]
# Outputs: [True, True, True, False, False]
a <= 3
b = [1 .. 10]
# Outputs: [False, True, False, True, False, True, False, True, False, True]
b % 2 == 0
This boolean array can be used in the filter function, to get only elements of the array that meet the condition. The filter function steps through both array inputs simultaneously, and returns elements from the first input where the corresponding element in the second input is true. For example, this gets all of the even numbers in an array:
b = [1 .. 10]
# Outputs: [2, 4, 6, 8, 10]
filter(b, b % 2 == 0)