Expected behaviour of println.(Array) (or @. println(Array) )

Hi.

Just to clarify a silly doubt. What is the expected behavior of

println.(x)

where x is an Array? I was expecting that println would be executed to each position of x, but

julia> x = rand(5)
5-element Array{Float64,1}:
0.08912877022448185
0.8256610270367024
0.5274878309082551
0.9455607916948552
0.7686464634951251

julia> println.(x)
0.08912877022448185
0.8256610270367024
0.5274878309082551
0.9455607916948552
0.7686464634951251
5-element Array{Nothing,1}:
nothing
nothing
nothing
nothing
nothing

I would like to understand the meaning of those Nothings.

Using Julia1.4.1

Thank you very much.

Well, it is simple:

When you are using a REPL the returned value is shown (except when it is nothing). println return none, and because you have running println for each value (with println.), you are obtaining an array of nothing. At different of nothing, that it is not shown in the REPL, an array of any type is always shown. This is the reason.

if you do not want the nothing, you can run

println.(x);

Anyway, it is in the REPL, running the code directly would not show anything different than the values of x.

I hope it is more clear now.

2 Likes

@CodeLenz One last comment:

the dot operator (as println.) is usually used when you want the return obtained.
If you only want to run the function for each value, you can use:

foreach(println, x)

foreach, at different of the vectorized, does not return anything.

3 Likes

Calling f.(x) returns an array (or other container) holding the value of f(x_i) for each x_i in x:

julia> f(x) = 2 * x
f (generic function with 1 method)

julia> f.([1, 2, 3])
3-element Array{Int64,1}:
 2
 4
 6

If f(x) returns nothing, then you will get a collection of nothings:

julia> g.([1, 2, 3])
3-element Array{Nothing,1}:
 nothing
 nothing
 nothing

println(x) returns nothing:

julia> result = println(1.0)
1.0

julia> result === nothing
true

so println.(x) returns a vector of nothings, which then get automatically printed because the REPL always prints out the return value of the last expression.

julia> println.([1, 2, 3])
1
2
3
3-element Array{Nothing,1}:
 nothing
 nothing
 nothing

Edit: @dmolina beat me to it!

I see!

I was missing the fact that println returns something (in this case, Nothing :slight_smile: ), since I was just looking at the output in the REPL.

Silly me, silly me.

Thanks a lot.