Re: Map Needs Merge

new topic     » goto parent     » topic index » view thread      » older message » newer message

The phix solution:

constant map1 = new_dict({{"key1","data1"}}), 
         map2 = new_dict({{"key2","data2"}}), 
         map3 = new_dict(map1) 
 
function merge(object key, object data, integer map3) 
    setd(key,data,map3) 
    return 1 
end function 
traverse_dict(routine_id("merge"),map3,map2) 
include builtins\map.e 
?{"map1:",pairs(map1)} 
?{"map2:",pairs(map2)} 
?{"map3:",pairs(map3)} 

output

{"map1:",{{"key1","data1"}}} 
{"map2:",{{"key2","data2"}}} 
{"map3:",{{"key1","data1"},{"key2","data2"}}} 

Obviously should the same key occur in map1 and map2, the data from map2 will overwrite the corresponding map1 value.

I have (just) added this as a second example to the traverse_dict() docs.

Note that other forms of merge are possible/may be required, for example if key is file size and data is a list of files of that size, the merge operation would probably want to concatenate rather than replace values, eg:

constant map1 = new_dict({{1234,{"this.txt"}}}), 
         map2 = new_dict({{1234,{"that.txt"}}}), 
         map3 = new_dict(map1) 
 
function merge(object key, object data, integer map3) 
    integer node = getd_index(key,map3) 
    if node=NULL then 
        setd(key,data,map3) 
    else 
        setd(key,getd_by_index(node,map3)&data,map3) 
    end if 
    return 1 
end function 
traverse_dict(routine_id("merge"),map3,map2) 
include builtins\map.e 
?{"map1:",pairs(map1)} 
?{"map2:",pairs(map2)} 
?{"map3:",pairs(map3)} 

output

{"map1:",{{1234,{"this.txt"}}}} 
{"map2:",{{1234,{"that.txt"}}}} 
{"map3:",{{1234,{"this.txt","that.txt"}}}} 

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu