Behavior of map function

I’ve been messing around with map and count for golfing purposes, and recently noticed this.

julia> map(i->print(i),[1,2,3,4])
12344-element Array{Nothing,1}:

julia> print(map(i->print(i),[1,2,3,4]))
1234[nothing, nothing, nothing, nothing]

How to explain that array of nothings there ?
Edit: Thanks to @jling and @bkamins, I understand both why the above is happening and how to (somewhat) avoid it

Originally, I was trying to evaluate the following function


at k=1,3,5,7, by doing map(a,[1,3,5,7]) but only the first value of k that I pass in the array prints the correct value, rest all produce 0.
Even if I try to evaluate a ‘normally’ as:

print("$(a(7)) and $(a(3))")

my second call always returns 0. Why is this happening ? (I’m on Julia 1.5.2 btw)

map allocates, print returns nothing, thus the result array.

1 Like

use foreach if you do not want to collect return values.


Thank you, that explains the test case’s behaviour.

But why is the second invocation of a always giving zero while the first invocation always gives the correct answer?

Edit: I get it, it’s because readlines exhausts the file after first invocation -_-

For golfing purposes, you can save a few strokes:


The first argument to map is a function. Your anonymous function i->print(i) is one function simply calling another.