Array Comprehensions
Example 1
function raindrops(n)
d = [(3,"Pling"), (5,"Plang"), (7, "Plong")]
s = [v for (k, v) in d if n % k == 0] |> join
s == "" ? string(n) : s
end
In the above code we first create an array of tuples. Then we use array comprehension to create an array of words. Each of the words in this new array is the value where the input number is a multiple of the corresponding key
Example 2
function secret_handshake(code)
secrets = [(1, "wink"), (2, "double blink"), (4, "close your eyes"), (8, "jump")]
r = [v for (k, v) in secrets if k & code == k]
code & 16 == 16 ? reverse(r) : r
end
This is a similar idea except that we are using the bit operation & to collect up all the words corresponding to the 1 bits in the input number. (The last line reverses the list if the input includes 16.)
Example 3
The general idea is that we enter some value into the array for each of a set of inputs, optionally with a filter clause. The filter clause can include an else.
a = [i*i for i in 1:10]
# Array a is all the square numbers from 1 to 100
b = [i*i for i in 1:10 if i%2==0]
# Array b is all the even square numbers from 4 to 100
c = [if i%2==0 i*i else 0 end for i in 1:10]
# Array c is the 10 element vector:
# 10-element Vector{Int64}: 0 4 0 16 0 36 0 64 0 100
Note that in this last case some rearranging of the code was needed so that the filter could include both what to do when the filter condition is true and what to do when it is false.
Example 4
Iteration through more than one input set of values is possible:
[i * j for i in 1:3 for j in 4:5]
# output: 6-element Vector{Int64}: 4 5 8 10 12 15
We get the cartesian product of the two inputs.
Multi-Dimensional array comprehension
Example 5
[x * y for x in 1:10, y in 1:10 ]
# Output:
10x10 Array{Int64,2}:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
There is some 'tricky to get right' syntax here. The rules are:
- multiple for statements will always return a vector
- including an if clause will always return a vector
- a single for with multiple comma separated loops will return a multidimensional array
An example of rule 1:
[x * y for x in 1:10 for y in 1:10 ]
This is the cartesian product of the two inputs as in example 4.
An example of rule 2 is:
[x * y for x in 1:3, y in 1:3 if (x*y)%2==0]
I have added an if to example 5 (and reduced the ranges) and we get a 1 dimensional subset of the cartesian product.
An example of rule 3 is example 5.