Julia: Feature request: `f.(x) do ... end`

Created on 9 Nov 2019  Â·  3Comments  Â·  Source: JuliaLang/julia

It looks like the dot-call syntax can't be used with the do notation at the moment:

julia> :(f.(x) do; end)
ERROR: syntax: missing comma or ) in argument list

But I think it is handy in some situations. For example:

first_nonempty_lines = open.(files) do io
    for line in eachline(io)
        isempty(line) || return line
    end
end

Does it make sense to support this?

broadcast

Most helpful comment

At first I wasn't convinced, but given that this works:

julia> files = ["a", "b", "c"];

julia> open.(io->println(io, "hi"), files, "w")
3-element Array{Nothing,1}:
 nothing
 nothing
 nothing

julia> open.(io->read(io, String), files, "r")
3-element Array{String,1}:
 "hi\n"
 "hi\n"
 "hi\n"

it seems natural that do should work as well, since it should be functionally (no pun intended) equivalent to specifying the function "normally."

EDIT: I changed my mind, pun retroactively intended.

All 3 comments

This reads to me as very surprising.

I personally find the below much cleaner.

map(files) do f
  open(f, "w") do io
    for line in eachline(io)
        isempty(line) || return line
    end
  end
end

One could do:

map(open.(files, "w")) do io

end

but of-course that runs the issue that open no longer automatically closes the io object...

Is this because .( is easy to miss when it is followed by a large do block?

If that's the case, wouldn't this be less of a problem in a more complex example?

open.(joinpath.(directory, stemnames .* ".jl")) do io
    for line in eachline(io)
        isempty(line) || return line
    end
end

At first I wasn't convinced, but given that this works:

julia> files = ["a", "b", "c"];

julia> open.(io->println(io, "hi"), files, "w")
3-element Array{Nothing,1}:
 nothing
 nothing
 nothing

julia> open.(io->read(io, String), files, "r")
3-element Array{String,1}:
 "hi\n"
 "hi\n"
 "hi\n"

it seems natural that do should work as well, since it should be functionally (no pun intended) equivalent to specifying the function "normally."

EDIT: I changed my mind, pun retroactively intended.

Was this page helpful?
0 / 5 - 0 ratings