Julia有没有switch啊

今天温习c语言时,突然发现Julia好像没有switch和case,文档里流程控制那块没有提到这个,难道是我看走眼了??

没有。可以用 http://kmsquire.github.io/Match.jl/latest/

Match.jl 貌似19就没更新了。

pattern match 当然用 MLStyle.jl 啦

1 个赞
module CSwitch

export @cswitch

# inspired by dcjones's Switch.jl
macro cswitch(constexpr, body)
    case2label = Dict{Any,Symbol}()
    flow = Expr(:block)
    end_label = gensym("end")
    default_label = end_label

    for arg in body.args
        if Meta.isexpr(arg, :macrocall) && arg.args[1] == Symbol("@case")
            label = gensym("case")
            case2label[arg.args[3]] = label
            labelexpr = Expr(:symboliclabel, label)
            push!(flow.args, labelexpr)
        elseif Meta.isexpr(arg, :macrocall) && arg.args[1] == Symbol("@default")
            default_label = gensym("default")
            labelexpr = Expr(:symboliclabel, default_label)
            push!(flow.args, labelexpr)
        elseif arg == Expr(:break)
            labelexpr = Expr(:symbolicgoto, end_label)
            push!(flow.args, labelexpr)
        else
            push!(flow.args, arg)
        end
    end
    push!(flow.args, Expr(:symboliclabel, end_label))

    jumptable = Expr(:block)
    for (case, label) in case2label
        condition = Expr(:call, :(==), constexpr, case)
        push!(jumptable.args, Expr(:if, condition, Expr(:symbolicgoto, label)))
    end
    push!(jumptable.args[end].args, Expr(:symbolicgoto, default_label))

    return esc(Expr(:block, jumptable, flow))
end

end # module
@enum test t=1 f=2
tester = t
@cswitch tester begin
       @case t
            x = 1
            break
       @case f
            x = 2
            break
end
x == 1
2 个赞

多分派可以代替一部分switch的功能

随手写了一段,仅供娱乐……

julia> json(x)=string(x)
json (generic function with 1 method)

julia> json(x::String)=begin io=IOBuffer();show(io,x);String(take!(io)) end
json (generic function with 2 methods)

julia> json(x::Array)="["*join(map(json,x),",")*"]"
json (generic function with 3 methods)

julia> json(x::Dict)="{"*join(map(((k,v),)->json(string(k))*":"*json(v),collect(pairs(x))),",")*"}"
json (generic function with 4 methods)

julia> a=Dict(:a=>1,:b=>[2,3],:c=>Dict(:x=>4.0,:y=>"5"))
Dict{Symbol,Any} with 3 entries:
  :a => 1
  :b => [2, 3]
  :c => Dict{Symbol,Any}(:y=>"5",:x=>4.0)

julia> json(a)
"{\"a\":1,\"b\":[2,3],\"c\":{\"y\":\"5\",\"x\":4.0}}"

格式化一下

{
   "a" : 1,
   "b" : [ 2, 3 ],
   "c" : {
      "y" : "5",
      "x" : 4.0
   }
}

FYI https://github.com/JuliaLang/julia/issues/18285