Moshi.jl and matching a dictionary as a pattern

I am currently porting to Julia some Python code that contains a lot of pattern matching for decoding JSON messages received via network socket, which are represented conveniently in Python as dictionaries.

Since Julia doesn’t have pattern matching in Base, I have decided to use Moshi.jl, since it looks like the most recommended implementation. However, it seems that it doesn’t support Dict as a pattern. Minimal working example:

using Moshi.Match: @match

msg = Dict(
   "error" => 2,
)

@match msg begin
   Dict("error" => x) => x
   _ => "unknown message"
end

The @match matches a wildcard pattern, i.e., returns string “unknown message”, but to my understanding it should match the Dict and return 2.

Am I doing something wrong here?

I will just comment that all of the dict-values you want to match follow this pattern, you could just do

@something(get(msg, "error", nothing),
           get(...),
           ...,
           "unknown message")
2 Likes

Indeed, I could do it like that in presented simple case, however, I am not so sure if it will work for more complex cases.

And it’s still baffles me, if it’s somehow possible with Moshi pattern matching syntax, since it’s more readable, at least for me.

@Roger-luo would know best.

Ironically, the spiritual predecessor MLStyle.jl can do this, documented here.

julia> Moshi.Match.@match msg begin
          Dict("error" => x) => x
          _ => "unknown message"
       end
"unknown message"

julia> MLStyle.@match msg begin
          Dict("error" => x) => x
          _ => "unknown message"
       end
2

I don’t use either so I can’t rule out Moshi doing this some other way, couldn’t find it in the docs though.

1 Like