thautwarm/MLStyle.jl

Capture dictionary keys and values.

Closed this issue · 1 comments

Hello, I'm trying to use pattern matching to match on a dictionary to filter our dictionaries with a certain number of elements as well as extract keys/values. Something like the following:

using MLStyle: @match

function capture_key(my_dict::Dict, key) 
    @match my_dict begin
        Dict(key => value) => process_value(value)
        Dict(key => value, other_key => other_value) => begin
            process_value(value)
            process_value(other_value)
            process_key(other_key)
        end
        _ => error("failed to match")
    end
end

In principle I can do this with guards but then I need to extract the values of the dictionary so this is mostly for readability of code.

Hello, I think what you wanted has been already supported for long:

julia> function capture_key(my_dict::Dict, key)
           @match my_dict begin
               Dict(key => value) => process_value(value)
               Dict(key => value, other_key => other_value) => begin
                   process_value(value)
                   process_value(other_value)
                   process_key(other_key)
               end
               _ => error("failed to match")
           end
       end

julia> process_value(v) = println("processing value: $v")
process_value (generic function with 1 method)

julia> process_key(k) = println("processing key: $k")
process_key (generic function with 1 method)

julia> capture_key(Dict("some_key" => 2), "some_key")
processing value: 2