<< operator for arrays

I guess the trouble is where you start trying to reference which gate to open with strings, but open("front") opens a file instead

Figured I’d add on to this thread because I had a similar thought. Mostly posting for posterity, as I assume likelihood of doing something like this is low.

Comparing the readability of these ways of calculating a result and adding it to a vector (assuming that it can’t be neatly done as a loop or generator):

a = []
push!(a, lengthyfunction1(lotsofargs))
push!(a, lengthyfunction2(lotsofargs))

a = []
b1 = lengthyfunction1(lotsofargs)
push!(a, b1)
b2 = lengthyfunction2(lotsofargs)
push!(a, b2)

a = Vector{Any}(undef, 2)
a[1] = lengthyfunction1(lotsofargs)
a[2] = lengthyfunction2(lotsofargs)

a = []
pusha! = Base.Fix1(push!, a)
lengthyfunction1(lotsofargs) |> pusha!
lengthyfunction2(lotsofargs) |> pusha!

a = []
←(x, y) = push!(x, y)
a ← lengthyfunction1(lotsofargs)
a ← lengthyfunction2(lotsofargs)

(or ↀ as noted upthread; just couldn’t find it in the latex lookup, so it might not be accessible enough)

To me the last option is definitely the cleanest. And it would be nice for a very common operation to have a clean operator. I hear the critique that it may be unclear that it is mutating though.

3 Likes

I prefer to define

module std
    export <<, endl, cout
    <<(io::IO, x) = (print(io, x); io)
    const endl = '\n'
    const cout = stdout
end

so that I can do:

julia> using .std; import .std: <<

julia> cout << "Hello world!" << endl;
Hello world!

which is so much cleaner and more natural than println.

26 Likes

[In case anyone misreads it, @stevengj does not do this. It’s a joke about C++’s notoriously confusing abuse of bitshift operators for input and output.]

16 Likes

Honestly, “enough power to make your code look and run like C++, and enough common sense to only choose the second” would be a pretty good moto for Julia.

15 Likes

\mapsfrom is valid in julia-REPL

1 Like

touché :laughing:

1 Like

Though @stevengj’s example is fine from the standpoint of not calling different actions the same thing, as his << is in a different name space.

1 Like

I assume you wanted to do

    <<(io::IO, x) = (print(io, x); io)

so that

const cerr = stderr
cerr << "Hello world!" << endl;

works as expected

6 Likes

Whoops, fixed. Forgetting to use the io argument in custom show-like methods seems to be a pretty common mistake, unfortunately.

9 Likes