How to define a set literal like Python?

In Python, we could write a set by {1, 2, 3}. In Julia, we have to write Set([1, 2, 3]). Is there a way to define a set literal the same way as Python?

If you define

Set(c...)=Set([c...])

then you can write
Set(1,2,3)

1 Like

Thanks, I have thought about

{}(args...) = Set([args...])

But that’s not a valid syntax.

Well you could use

macro s_str(x)
     @assert x[1] == '{' && x[end] == '}'
     :(Set([$(esc(Meta.parse(x[2:(end - 1)])))...]))
end

but s"{1, 3}" isn’t much of an improvement over Set([1, 3])

2 Likes

Note that redefining Set() in this way is type piracy and is likely to have unforeseen consequences (like silently breaking completely unrelated code!) For more information, see: https://docs.julialang.org/en/v1/manual/style-guide/index.html#Avoid-type-piracy-1

7 Likes

You can probably overload braces and/or bracescat.
They are the special-forms for those expressions, and they get translated to by the parser.
See https://github.com/JuliaLang/julia/pull/22942

Not tested but I think:

Base.braces(args...) = Set([args...])

I would not do that, but you can do it.

Those are expression heads in the AST, not functions that you can overload. You could define a macro (after installing MacroTools.jl):

import MacroTools
macro sets(expr)
    esc(MacroTools.postwalk(expr) do ex
        Meta.isexpr(ex, :braces) ? :(Set($(Expr(:tuple, ex.args...)))) : ex
    end)
end

and then you can do, for example:

julia> @sets {3,4,5} ∪ {3,5,6}
Set([4, 3, 5, 6])

Defining a macro like this to locally modify syntax is safe and can be convenient if you need domain-specific expressions. I wouldn’t do it merely to make Julia syntax look like Python syntax, however — if you are programming in Julia, you should use Julia idioms.

10 Likes

But to write an array in python, you need to write array([1, 2, 3, 4]). Since arrays are more commonly used than sets, have you asked them to change their syntax to be more like Julia’s?

3 Likes

No, I haven’t. Let me clarify myself: When I am studying a language, I want to know whether I can do the same thing as the language I have learned. I just want to explore what Julia can do to understand it better, which does not mean I think Python is superior to Julia. I ask this question does not mean I really want to write a set literal. But I am still grateful to all the help you gave, thank you!

You already knew that you could do the same thing, because you knew you could write Set([1, 2, 3]). Asking to do the same thing with the same syntax as your old language, on the other hand, has limited value in learning a new language — you should generally strive to learn the native idioms.

3 Likes