DEV Community

Cover image for Learning Julia (5): array comprehension
Z. QIU
Z. QIU

Posted on • Updated on

Learning Julia (5): array comprehension

We can use [expr(i) for i in somelist] to obtain a list in Python, which is so called List comprehension. In Julia, we can generate arrays in a similar way.

a = [i*i for i in 1:10]
println("a: ", a, ", typeof(a): ", typeof(a))

Enter fullscreen mode Exit fullscreen mode

Execution output:

Alt Text

We see that we get an array using the same method as in Python.
Comprehensions can also be written without the enclosing square brackets, producing an object known as a generator (Base.Generator type).

g = (1/n for n=1:100)
println("g: ", g)
Enter fullscreen mode Exit fullscreen mode

Execution output:
Alt Text

I tried some more complex array comprehensions and there are some slight differences from Python (ELSE-statement can be ignored but is highly recommended):

a1 = [i*i  for i in 1:10 if i%2==0]          # IF-condition filter at the end 
a2 = [if i%2==0 i*i else 0 end  for i in 1:10 ]   # IF-ELSE statements ahead of FOR-statement; "end" keyword is required, whichis main difference with Python
a3 = [if i%2==0 i*i  end  for i in 1:10 ]    # IF-statement without ELSE-condition definition, which yields 'nothing' in the result, "end" keyword is required
a4 = [i*j for i in 1:3 for j in 4:6]  
println("a1: ", a1) 
println("a2: ", a2) 
println("a3: ", a3) 
println("a4: ", a4) 
Enter fullscreen mode Exit fullscreen mode

Execution output:
Alt Text

Same as in Python, map() is also implemented:


# map() with anonymous functions
a5 = map(x -> x*x, 1:5)          
a6 = map(x -> x%2==0 ? x*x : 0, 1:5)
g = (n+1 for n=1:10)
a7 = map(x -> x*x, g)   # takes a generator object
println("a5: ", a5) 
println("a6: ", a6) 
println("a7: ", a7) 
println(" ")

Enter fullscreen mode Exit fullscreen mode

Execution output:
Alt Text

I tried map() and reduce() using given functions:

function func(x::Int)
    if x%2 == 0
        return x
    else 
        return 0
    end
end

a = map(func, 2:2:9)   #  supplies a one-argument function 

println("a: ", a)    # => [2, 4, 6, 8]

function foo(x::Int, y::Int)
    return x*10+y
end

b = reduce(foo, a)
println("b: ", b) 

c = mapreduce(func,foo, 2:2:9)
println("c: ", c) 
Enter fullscreen mode Exit fullscreen mode

Execution output:
Alt Text

Top comments (0)