Associative array/Merging: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 47: Line 47:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V base = [‘name’ = ‘Rocket Skates’, ‘price’ = ‘12.75’, ‘color’ = ‘yellow’]
<syntaxhighlight lang=11l>V base = [‘name’ = ‘Rocket Skates’, ‘price’ = ‘12.75’, ‘color’ = ‘yellow’]
V update = [‘price’ = ‘15.25’, ‘color’ = ‘red’, ‘year’ = ‘1974’]
V update = [‘price’ = ‘15.25’, ‘color’ = ‘red’, ‘year’ = ‘1974’]


Line 53: Line 53:
result.update(update)
result.update(update)


print(result)</lang>
print(result)</syntaxhighlight>


{{out}}
{{out}}
Line 61: Line 61:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_Io;
<syntaxhighlight lang=Ada>with Ada.Text_Io;
with Ada.Containers.Indefinite_Ordered_Maps;
with Ada.Containers.Indefinite_Ordered_Maps;


Line 129: Line 129:
New_Line;
New_Line;


end Merge_Maps;</lang>
end Merge_Maps;</syntaxhighlight>
{{out}}
{{out}}
<pre>Original:
<pre>Original:
Line 150: Line 150:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses the associative array implementations in [[ALGOL_68/prelude]].
Uses the associative array implementations in [[ALGOL_68/prelude]].
<lang algol68># associative array merging #
<syntaxhighlight lang=algol68># associative array merging #
# the modes allowed as associative array element values - change to suit #
# the modes allowed as associative array element values - change to suit #
Line 201: Line 201:
);
);
e := NEXT c
e := NEXT c
OD</lang>
OD</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 214: Line 214:
The method with AppleScript "records" is to concatenate them. The result is a third record containing the labels from both contributors, the values from the record to the left of the operator being kept where labels are shared. The bars with some of the labels below are to distinguish them as "user" labels from tokenised ones that are provided as standards for use by scriptable applications and scripting additions. However, merging records works with tokenised labels too.
The method with AppleScript "records" is to concatenate them. The result is a third record containing the labels from both contributors, the values from the record to the left of the operator being kept where labels are shared. The bars with some of the labels below are to distinguish them as "user" labels from tokenised ones that are provided as standards for use by scriptable applications and scripting additions. However, merging records works with tokenised labels too.


<lang applescript>set baseRecord to {|name|:"Rocket Skates", price:12.75, |color|:"yellow"}
<syntaxhighlight lang=applescript>set baseRecord to {|name|:"Rocket Skates", price:12.75, |color|:"yellow"}
set updateRecord to {price:15.25, |color|:"red", |year|:1974}
set updateRecord to {price:15.25, |color|:"red", |year|:1974}


set mergedRecord to updateRecord & baseRecord
set mergedRecord to updateRecord & baseRecord
return mergedRecord</lang>
return mergedRecord</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>{price:15.25, |color|:"red", |year|:1974, |name|:"Rocket Skates"}</lang>
<syntaxhighlight lang=applescript>{price:15.25, |color|:"red", |year|:1974, |name|:"Rocket Skates"}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>details: #[name: "Rocket Skates" price: 12.75 colour: 'yellow]
<syntaxhighlight lang=rebol>details: #[name: "Rocket Skates" price: 12.75 colour: 'yellow]
newDetails: extend details #[price: 15.25 colour: 'red year: 1974]
newDetails: extend details #[price: 15.25 colour: 'red year: 1974]


print newDetails</lang>
print newDetails</syntaxhighlight>


{{out}}
{{out}}
Line 235: Line 235:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>merge(base, update){
<syntaxhighlight lang=AutoHotkey>merge(base, update){
Merged := {}
Merged := {}
for k, v in base
for k, v in base
Line 242: Line 242:
Merged[k] := v
Merged[k] := v
return Merged
return Merged
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>base := {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
Examples:<syntaxhighlight lang=AutoHotkey>base := {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update := {"price":15.25, "color":"red", "year":1974}
update := {"price":15.25, "color":"red", "year":1974}
Merged := merge(base, update)
Merged := merge(base, update)
for k, v in Merged
for k, v in Merged
result .= k " : " v "`n"
result .= k " : " v "`n"
MsgBox % result</lang>
MsgBox % result</syntaxhighlight>
Outputs:<pre>color : red
Outputs:<pre>color : red
name : Rocket Skates
name : Rocket Skates
Line 255: Line 255:


=={{header|AWK}}==
=={{header|AWK}}==
<lang AWK>
<syntaxhighlight lang=AWK>
# syntax: GAWK -f ASSOCIATIVE_ARRAY_MERGING.AWK
# syntax: GAWK -f ASSOCIATIVE_ARRAY_MERGING.AWK
#
#
Line 283: Line 283:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 304: Line 304:


=={{header|B4X}}==
=={{header|B4X}}==
<lang b4x>Dim m1 As Map = CreateMap("name": "Rocket Skates", "price": 12.75, "color": "yellow")
<syntaxhighlight lang=b4x>Dim m1 As Map = CreateMap("name": "Rocket Skates", "price": 12.75, "color": "yellow")
Dim m2 As Map = CreateMap("price": 15.25, "color": "red", "year": 1974)
Dim m2 As Map = CreateMap("price": 15.25, "color": "red", "year": 1974)
Dim merged As Map
Dim merged As Map
Line 313: Line 313:
Next
Next
Next
Next
Log(merged)</lang>
Log(merged)</syntaxhighlight>


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang bacon>DECLARE base$, update$, merge$ ASSOC STRING
<syntaxhighlight lang=bacon>DECLARE base$, update$, merge$ ASSOC STRING


base$("name") = "Rocket Skates"
base$("name") = "Rocket Skates"
Line 342: Line 342:
FOR x$ IN OBTAIN$(merge$)
FOR x$ IN OBTAIN$(merge$)
PRINT x$, " : ", merge$(x$)
PRINT x$, " : ", merge$(x$)
NEXT</lang>
NEXT</syntaxhighlight>
{{out}}
{{out}}
<pre>Base array
<pre>Base array
Line 361: Line 361:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang=cpp>#include <iostream>
#include <string>
#include <string>
#include <map>
#include <map>
Line 388: Line 388:
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 399: Line 399:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 424: Line 424:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 433: Line 433:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang Clojure>
<syntaxhighlight lang=Clojure>
(defn update-map [base update]
(defn update-map [base update]
(merge base update))
(merge base update))
Line 443: Line 443:
"color" "red"
"color" "red"
"year" "1974"})
"year" "1974"})
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 451: Line 451:


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang crystal>base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
<syntaxhighlight lang=crystal>base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
update = { "price" => 15.25, "color" => "red", "year" => 1974 }
update = { "price" => 15.25, "color" => "red", "year" => 1974 }


puts base.merge(update)</lang>
puts base.merge(update)</syntaxhighlight>


{{out}}
{{out}}
Line 462: Line 462:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
In Common Lisp, the value of a key in an alist or a plist is defined as the first value in the list with a matching key or indicator. Thus, all that is necessary to implement this algorithm for either is the following:
In Common Lisp, the value of a key in an alist or a plist is defined as the first value in the list with a matching key or indicator. Thus, all that is necessary to implement this algorithm for either is the following:
<lang lisp>
<syntaxhighlight lang=lisp>
(append list2 list1)
(append list2 list1)
</syntaxhighlight>
</lang>


These implementations for alists and plists are more complicated, but avoid duplicate keys in the results:
These implementations for alists and plists are more complicated, but avoid duplicate keys in the results:
<lang lisp>
<syntaxhighlight lang=lisp>
(defun merge-alists (alist1 alist2)
(defun merge-alists (alist1 alist2)
(nconc
(nconc
Line 483: Line 483:
:do (setf (getf res key) val))
:do (setf (getf res key) val))
res))
res))
</syntaxhighlight>
</lang>


=={{header|Dart}}==
=={{header|Dart}}==
<lang javascript>
<syntaxhighlight lang=javascript>
main() {
main() {
var base = {
var base = {
Line 508: Line 508:


}
}
</syntaxhighlight>
</lang>
=={{header|Delphi}}==
=={{header|Delphi}}==
{{libheader| System.Generics.Collections}}
{{libheader| System.Generics.Collections}}
{{Trans|C#}}
{{Trans|C#}}
<lang Delphi>
<syntaxhighlight lang=Delphi>
program Associative_arrayMerging;
program Associative_arrayMerging;


Line 555: Line 555:
end.
end.


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 565: Line 565:
=={{header|Elixir}}==
=={{header|Elixir}}==
Elixir has a built-in hashmap type, called [https://hexdocs.pm/elixir/Map.html Map].
Elixir has a built-in hashmap type, called [https://hexdocs.pm/elixir/Map.html Map].
<lang Elixir>base = %{name: "Rocket Skates", price: 12.75, color: "yellow"}
<syntaxhighlight lang=Elixir>base = %{name: "Rocket Skates", price: 12.75, color: "yellow"}
update = %{price: 15.25, color: "red", year: 1974}
update = %{price: 15.25, color: "red", year: 1974}
result = Map.merge(base, update)
result = Map.merge(base, update)
IO.inspect(result)</lang>
IO.inspect(result)</syntaxhighlight>
{{out}}
{{out}}
<pre>%{color: "red", name: "Rocket Skates", price: 15.25, year: 1974}</pre>
<pre>%{color: "red", name: "Rocket Skates", price: 15.25, year: 1974}</pre>
The above sample uses [https://hexdocs.pm/elixir/Atom.html atoms] as the key type. If strings are needed, the <code>base</code> map would look like this:
The above sample uses [https://hexdocs.pm/elixir/Atom.html atoms] as the key type. If strings are needed, the <code>base</code> map would look like this:
<lang Elixir>base = %{"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}</lang>
<syntaxhighlight lang=Elixir>base = %{"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang=fsharp>
type N = |Price of float|Name of string|Year of int|Colour of string
type N = |Price of float|Name of string|Year of int|Colour of string
let n=Map<string,N>[("name",Name("Rocket Skates"));("price",Price(12.75));("colour",Colour("yellow"))]
let n=Map<string,N>[("name",Name("Rocket Skates"));("price",Price(12.75));("colour",Colour("yellow"))]
Line 581: Line 581:
let ng=(Map.toList n)@(Map.toList g)|>Map.ofList
let ng=(Map.toList n)@(Map.toList g)|>Map.ofList
printfn "%A" ng
printfn "%A" ng
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 593: Line 593:
The <code>assoc-union</code> word does this. <code>assoc-union!</code> is a variant that mutates the first associative array.
The <code>assoc-union</code> word does this. <code>assoc-union!</code> is a variant that mutates the first associative array.
{{works with|Factor|0.99 2019-10-06}}
{{works with|Factor|0.99 2019-10-06}}
<lang factor>USING: assocs prettyprint ;
<syntaxhighlight lang=factor>USING: assocs prettyprint ;


{ { "name" "Rocket Skates" } { "price" 12.75 } { "color" "yellow" } }
{ { "name" "Rocket Skates" } { "price" 12.75 } { "color" "yellow" } }
{ { "price" 15.25 } { "color" "red" } { "year" 1974 } }
{ { "price" 15.25 } { "color" "red" } { "year" 1974 } }
assoc-union .</lang>
assoc-union .</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 609: Line 609:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang=go>package main


import "fmt"
import "fmt"
Line 631: Line 631:
result := merge(base, update)
result := merge(base, update)
fmt.Println(result)
fmt.Println(result)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 641: Line 641:
There are various approaches, all of which would be strictly typed.<br>
There are various approaches, all of which would be strictly typed.<br>
For example, if we want to treat the input and output records as all sharing the same type:
For example, if we want to treat the input and output records as all sharing the same type:
<lang haskell>data Item = Item
<syntaxhighlight lang=haskell>data Item = Item
{ name :: Maybe String
{ name :: Maybe String
, price :: Maybe Float
, price :: Maybe Float
Line 657: Line 657:
itemFromMerge
itemFromMerge
(Item (Just "Rocket Skates") (Just 12.75) (Just "yellow") Nothing)
(Item (Just "Rocket Skates") (Just 12.75) (Just "yellow") Nothing)
(Item Nothing (Just 15.25) (Just "red") (Just 1974))</lang>
(Item Nothing (Just 15.25) (Just "red") (Just 1974))</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Item {name = Just "Rocket Skates", price = Just 15.25, color = Just "red", year = Just 1974}</pre>
<pre>Item {name = Just "Rocket Skates", price = Just 15.25, color = Just "red", year = Just 1974}</pre>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang unicon>procedure main()
<syntaxhighlight lang=unicon>procedure main()
local base, update, master, f, k
local base, update, master, f, k


Line 683: Line 683:
write(k, " = ", master[k])
write(k, " = ", master[k])
}
}
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 693: Line 693:


=={{header|J}}==
=={{header|J}}==
<syntaxhighlight lang=J>
<lang J>
merge=: ,. NB. use: update merge original
merge=: ,. NB. use: update merge original
compress=: #"1~ ~:@:keys
compress=: #"1~ ~:@:keys
Line 700: Line 700:
get=: [: > ((i.~ keys)~ <)~ { values@:] NB. key get (associative array)
get=: [: > ((i.~ keys)~ <)~ { values@:] NB. key get (associative array)
pair=: [: |: <;._2;._2
pair=: [: |: <;._2;._2
</syntaxhighlight>
</lang>
Exercise the definitions. Interactive J prompts with 3 space indentation.
Exercise the definitions. Interactive J prompts with 3 space indentation.
<pre>
<pre>
Line 752: Line 752:


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.util.*;
<syntaxhighlight lang=java>import java.util.*;


class MergeMaps {
class MergeMaps {
Line 770: Line 770:
System.out.println(result);
System.out.println(result);
}
}
}</lang>
}</syntaxhighlight>
{{output}}
{{output}}
<pre>{name=Rocket Skates, color=red, year=1974, price=15.25}</pre>
<pre>{name=Rocket Skates, color=red, year=1974, price=15.25}</pre>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>(() => {
<syntaxhighlight lang=javascript>(() => {
'use strict';
'use strict';


Line 792: Line 792:
null, 2
null, 2
))
))
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>{
<pre>{
Line 845: Line 845:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>
<syntaxhighlight lang=scala>
fun main() {
fun main() {
val base = HashMap<String,String>()
val base = HashMap<String,String>()
Line 865: Line 865:
println("merged: $merged")
println("merged: $merged")
}
}
</syntaxhighlight>
</lang>
{{Output}}
{{Output}}
<pre>
<pre>
Line 874: Line 874:


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>base = {name="Rocket Skates", price=12.75, color="yellow"}
<syntaxhighlight lang=Lua>base = {name="Rocket Skates", price=12.75, color="yellow"}
update = {price=15.25, color="red", year=1974}
update = {price=15.25, color="red", year=1974}


Line 891: Line 891:
for key,val in pairs(result) do
for key,val in pairs(result) do
print(string.format("%s: %s", key, val))
print(string.format("%s: %s", key, val))
end</lang>
end</syntaxhighlight>


{{output}}
{{output}}
Line 900: Line 900:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>a1 = <|"name" -> "Rocket Skates", "price" -> 12.75, "color" -> "yellow"|>;
<syntaxhighlight lang=Mathematica>a1 = <|"name" -> "Rocket Skates", "price" -> 12.75, "color" -> "yellow"|>;
a2 = <|"price" -> 15.25, "color" -> "red", "year" -> 1974|>;
a2 = <|"price" -> 15.25, "color" -> "red", "year" -> 1974|>;
Merge[{a1, a2}, Last]</lang>
Merge[{a1, a2}, Last]</syntaxhighlight>
{{out}}
{{out}}
<pre><|"name" -> "Rocket Skates", "price" -> 15.25, "color" -> "red", "year" -> 1974|></pre>
<pre><|"name" -> "Rocket Skates", "price" -> 15.25, "color" -> "red", "year" -> 1974|></pre>
Line 908: Line 908:
=={{header|MiniScript}}==
=={{header|MiniScript}}==
MiniScript supports merging maps with the + operator.
MiniScript supports merging maps with the + operator.
<lang MiniScript>base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
<syntaxhighlight lang=MiniScript>base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
update = {"price":15.25, "color":"red", "year":1974}


result = base + update
result = base + update


print result</lang>
print result</syntaxhighlight>


{{output}}
{{output}}
Line 919: Line 919:


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import tables
<syntaxhighlight lang=Nim>import tables


let t1 = {"name": "Rocket Skates", "price": "12.75", "color": "yellow"}.toTable
let t1 = {"name": "Rocket Skates", "price": "12.75", "color": "yellow"}.toTable
Line 928: Line 928:
t3[key] = value
t3[key] = value


echo t3</lang>
echo t3</syntaxhighlight>


{{out}}
{{out}}
Line 935: Line 935:
=={{header|Objective-C}}==
=={{header|Objective-C}}==
{{works with|Cocoa}}
{{works with|Cocoa}}
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang=objc>#import <Foundation/Foundation.h>


int main(void) {
int main(void) {
Line 948: Line 948:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{output}}
{{output}}
<pre>{
<pre>{
Line 964: Line 964:


Helper code for all 3 versions:
Helper code for all 3 versions:
<lang OCaml>
<syntaxhighlight lang=OCaml>
type ty =
type ty =
| TFloat of float
| TFloat of float
Line 981: Line 981:
Printf.printf "%s: %s\n" key (string_of_ty el)
Printf.printf "%s: %s\n" key (string_of_ty el)
;;
;;
</syntaxhighlight>
</lang>


Association list : naive and functional approach.
Association list : naive and functional approach.
<lang OCaml>
<syntaxhighlight lang=OCaml>
let l1 : assoc list = [
let l1 : assoc list = [
("name", TString "Rocket Skates");
("name", TString "Rocket Skates");
Line 1,007: Line 1,007:


let l' = merge_assoc_list l1 l2 ;;
let l' = merge_assoc_list l1 l2 ;;
</syntaxhighlight>
</lang>


Binary tree/Map functor : proper functional approach.
Binary tree/Map functor : proper functional approach.
{{works with|OCaml|above 4.03 for union function}}
{{works with|OCaml|above 4.03 for union function}}
<lang OCaml>
<syntaxhighlight lang=OCaml>
module StringMap = Map.Make(String) ;;
module StringMap = Map.Make(String) ;;


Line 1,037: Line 1,037:


print_map m' ;;
print_map m' ;;
</syntaxhighlight>
</lang>


Hash table : imperative/mutable approach.
Hash table : imperative/mutable approach.
<lang OCaml>
<syntaxhighlight lang=OCaml>
(* Updates the base table with the bindings from add *)
(* Updates the base table with the bindings from add *)
let hash_merge (base : (string, ty) Hashtbl.t) (add : (string, ty) Hashtbl.t) : unit =
let hash_merge (base : (string, ty) Hashtbl.t) (add : (string, ty) Hashtbl.t) : unit =
Line 1,061: Line 1,061:


print_hashtbl h1 ;;
print_hashtbl h1 ;;
</syntaxhighlight>
</lang>


=={{header|Ol}}==
=={{header|Ol}}==
Since version 3.1.1 function `ff-union` changed from `(ff-union a1 a2 collide)` to `(ff-union collide a1 a2 ...)`!
Since version 3.1.1 function `ff-union` changed from `(ff-union a1 a2 collide)` to `(ff-union collide a1 a2 ...)`!


<lang scheme>
<syntaxhighlight lang=scheme>
(define a1 {
(define a1 {
'name "Rocket Skates"
'name "Rocket Skates"
Line 1,084: Line 1,084:
(define (collide a b) b) ; will use new key value
(define (collide a b) b) ; will use new key value
(print "merged a1 a2: " (ff-union collide a1 a2))
(print "merged a1 a2: " (ff-union collide a1 a2))
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,093: Line 1,093:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use strict;
<syntaxhighlight lang=perl>use strict;
use warnings;
use warnings;


Line 1,107: Line 1,107:
$merge{$_} = [$base{$_}] for keys %base;
$merge{$_} = [$base{$_}] for keys %base;
push @{$merge{$_}}, $more{$_} for keys %more;
push @{$merge{$_}}, $more{$_} for keys %more;
printf "%-7s %s\n", $_, join ', ', @{$merge{$_}} for sort keys %merge;</lang>
printf "%-7s %s\n", $_, join ', ', @{$merge{$_}} for sort keys %merge;</syntaxhighlight>
{{output}}
{{output}}
<pre>Update
<pre>Update
Line 1,122: Line 1,122:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">d1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">({{</span><span style="color: #008000;">"name"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Rocket Skates"</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"price"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12.75</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"color"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"yellow"</span><span style="color: #0000FF;">}}),</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">d1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">({{</span><span style="color: #008000;">"name"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Rocket Skates"</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"price"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12.75</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"color"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"yellow"</span><span style="color: #0000FF;">}}),</span>
Line 1,131: Line 1,131:
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #000000;">map</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #000000;">map</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">pairs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d3</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">pairs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d3</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,138: Line 1,138:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang=Phixmonti>include ..\Utilitys.pmt


def scand /# dict key -- dict n #/
def scand /# dict key -- dict n #/
Line 1,184: Line 1,184:


pstack
pstack
</syntaxhighlight>
</lang>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?
<syntaxhighlight lang=php><?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
Line 1,193: Line 1,193:
$result = $update + $base; // Notice that the order is reversed
$result = $update + $base; // Notice that the order is reversed
print_r($result);
print_r($result);
?></lang>
?></syntaxhighlight>
{{output}}
{{output}}
<pre>Array
<pre>Array
Line 1,204: Line 1,204:


Alternative:
Alternative:
<lang php><?
<syntaxhighlight lang=php><?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
Line 1,210: Line 1,210:
$result = array_merge($base, $update);
$result = array_merge($base, $update);
print_r($result);
print_r($result);
?></lang>
?></syntaxhighlight>
{{output}}
{{output}}
<pre>Array
<pre>Array
Line 1,221: Line 1,221:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>NewMap m1.s()
<syntaxhighlight lang=PureBasic>NewMap m1.s()
NewMap m2.s()
NewMap m2.s()
NewMap m3.s()
NewMap m3.s()
Line 1,241: Line 1,241:
ForEach m3()
ForEach m3()
Debug MapKey(m3())+" : "+m3()
Debug MapKey(m3())+" : "+m3()
Next</lang>
Next</syntaxhighlight>
{{out}}
{{out}}
<pre>price : 15.25
<pre>price : 15.25
Line 1,251: Line 1,251:
As of Python 3.5, this can be solved with the dictionary unpacking operator.
As of Python 3.5, this can be solved with the dictionary unpacking operator.
{{works with|Python|3.5+}}
{{works with|Python|3.5+}}
<lang Python>base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
<syntaxhighlight lang=Python>base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
update = {"price":15.25, "color":"red", "year":1974}


result = {**base, **update}
result = {**base, **update}


print(result)</lang>
print(result)</syntaxhighlight>
{{output}}
{{output}}
<pre>{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}</pre>
<pre>{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}</pre>


;Alternative:
;Alternative:
<lang Python>base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
<syntaxhighlight lang=Python>base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
update = {"price":15.25, "color":"red", "year":1974}


Line 1,267: Line 1,267:
result.update(update)
result.update(update)


print(result)</lang>
print(result)</syntaxhighlight>
{{output}}
{{output}}
<pre>{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}</pre>
<pre>{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}</pre>
Line 1,273: Line 1,273:
;New alternative using '|'
;New alternative using '|'


<lang python>Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
<syntaxhighlight lang=python>Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
Type "help", "copyright", "credits" or "license()" for more information.
>>> base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
>>> base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
Line 1,280: Line 1,280:
>>> result
>>> result
{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}
{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}
>>> </lang>
>>> </syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>#lang racket/base
<syntaxhighlight lang=racket>#lang racket/base


(require racket/hash)
(require racket/hash)
Line 1,300: Line 1,300:


(hash-union base-data update-data #:combine (λ (a b) b)))
(hash-union base-data update-data #:combine (λ (a b) b)))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,310: Line 1,310:
I must say I somewhat disagree with the terminology. The requested operation is an update not a merge. Demonstrate both an update and a merge. Associative arrays are commonly called hashes in Raku.
I must say I somewhat disagree with the terminology. The requested operation is an update not a merge. Demonstrate both an update and a merge. Associative arrays are commonly called hashes in Raku.


<lang perl6># Show original hashes
<syntaxhighlight lang=perl6># Show original hashes
say my %base = :name('Rocket Skates'), :price<12.75>, :color<yellow>;
say my %base = :name('Rocket Skates'), :price<12.75>, :color<yellow>;
say my %update = :price<15.25>, :color<red>, :year<1974>;
say my %update = :price<15.25>, :color<red>, :year<1974>;
Line 1,325: Line 1,325:


# Demonstrate unmutated hashes
# Demonstrate unmutated hashes
say "\n", %base, "\n", %update;</lang>
say "\n", %base, "\n", %update;</syntaxhighlight>
{{out}}
{{out}}
<pre>{color => yellow, name => Rocket Skates, price => 12.75}
<pre>{color => yellow, name => Rocket Skates, price => 12.75}
Line 1,365: Line 1,365:
The double quotes that surround the string (character) items (as shown in the task's preamble) weren't included for this presentation,
The double quotes that surround the string (character) items (as shown in the task's preamble) weren't included for this presentation,
<br>although they could easily be added.
<br>although they could easily be added.
<lang rexx>/*REXX program merges two associative arrays (requiring an external list of indices). */
<syntaxhighlight lang=rexx>/*REXX program merges two associative arrays (requiring an external list of indices). */
$.= /*define default value(s) for arrays. */
$.= /*define default value(s) for arrays. */
@.wAAn= 21; @.wKey= 7; @.wVal= 7 /*max widths of: AAname, keys, values.*/
@.wAAn= 21; @.wKey= 7; @.wVal= 7 /*max widths of: AAname, keys, values.*/
Line 1,397: Line 1,397:
say center(AAn, @.wAAn) right(key, @.wKey) $.AAn.key /*show some information.*/
say center(AAn, @.wAAn) right(key, @.wKey) $.AAn.key /*show some information.*/
end /*j*/
end /*j*/
return</lang>
return</syntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
<pre>
Line 1,418: Line 1,418:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang=ring>
load "stdlib.ring"
load "stdlib.ring"


Line 1,442: Line 1,442:
see list1[n][1] + " = " + list1[n][2] + nl
see list1[n][1] + " = " + list1[n][2] + nl
next
next
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,452: Line 1,452:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
<syntaxhighlight lang=ruby>base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
update = {"price" => 15.25, "color" => "red", "year" => 1974}
update = {"price" => 15.25, "color" => "red", "year" => 1974}


result = base.merge(update)
result = base.merge(update)
p result</lang>
p result</syntaxhighlight>
{{output}}
{{output}}
<pre>{"name"=>"Rocket Skates", "price"=>15.25, "color"=>"red", "year"=>1974}</pre>
<pre>{"name"=>"Rocket Skates", "price"=>15.25, "color"=>"red", "year"=>1974}</pre>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::collections::HashMap;
<syntaxhighlight lang=rust>use std::collections::HashMap;


fn main() {
fn main() {
Line 1,478: Line 1,478:
println!("{:#?}", original);
println!("{:#?}", original);
}
}
</syntaxhighlight>
</lang>
{{output}}
{{output}}
<pre>{
<pre>{
Line 1,493: Line 1,493:
in an alist. Hence, a merge may be implemented by simply appending the update alist to the
in an alist. Hence, a merge may be implemented by simply appending the update alist to the
front of the base alist. The downside is this leaves a bunch of useless junk in the alist.
front of the base alist. The downside is this leaves a bunch of useless junk in the alist.
<lang scheme>; Merge alists by appending the update list onto the front of the base list.
<syntaxhighlight lang=scheme>; Merge alists by appending the update list onto the front of the base list.
; (The extra '() is so that append doesn't co-opt the second list.)
; (The extra '() is so that append doesn't co-opt the second list.)
(define append-alists
(define append-alists
Line 1,512: Line 1,512:
(unless (null? keys)
(unless (null? keys)
(printf "~s -> ~s~%" (car keys) (cdr (assoc (car keys) merged)))
(printf "~s -> ~s~%" (car keys) (cdr (assoc (car keys) merged)))
(loop (cdr keys))))))</lang>
(loop (cdr keys))))))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,528: Line 1,528:
This is more true to the intent of the Task. It generates a new alist with only the key/value
This is more true to the intent of the Task. It generates a new alist with only the key/value
pairs needed.
pairs needed.
<lang scheme>; Merge the given alists. Prefer the items from the "update" alist.
<syntaxhighlight lang=scheme>; Merge the given alists. Prefer the items from the "update" alist.
; Returns a new list; the argument lists are not modified.
; Returns a new list; the argument lists are not modified.
(define merge-alists
(define merge-alists
Line 1,554: Line 1,554:
(unless (null? keys)
(unless (null? keys)
(printf "~s -> ~s~%" (car keys) (cdr (assoc (car keys) merged)))
(printf "~s -> ~s~%" (car keys) (cdr (assoc (car keys) merged)))
(loop (cdr keys))))))</lang>
(loop (cdr keys))))))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,569: Line 1,569:
=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
In addition to setting individual property values, SenseTalk includes 5 built-in operations for modifying property lists, to: add properties, replace properties, remove properties, retain properties, and rename properties. The operation to replace properties is needed for this task.
In addition to setting individual property values, SenseTalk includes 5 built-in operations for modifying property lists, to: add properties, replace properties, remove properties, retain properties, and rename properties. The operation to replace properties is needed for this task.
<lang sensetalk>set base to {name:"Rocket Skates", price:12.75, color:"yellow"}
<syntaxhighlight lang=sensetalk>set base to {name:"Rocket Skates", price:12.75, color:"yellow"}


set update to {price:15.25, color:"red", year:1974}
set update to {price:15.25, color:"red", year:1974}
Line 1,582: Line 1,582:
replace properties of update in base
replace properties of update in base
put "Base after update: " & base
put "Base after update: " & base
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,592: Line 1,592:


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>base := Dictionary withAssociations:{
<syntaxhighlight lang=smalltalk>base := Dictionary withAssociations:{
'name'-> 'Rocket Skates' .
'name'-> 'Rocket Skates' .
'price' -> 12.75 .
'price' -> 12.75 .
Line 1,606: Line 1,606:
declareAllFrom:update.
declareAllFrom:update.


Transcript showCR: result.</lang>
Transcript showCR: result.</syntaxhighlight>
{{out}}
{{out}}
<pre>Dictionary(name->Rocket Skates price->15.25 year->1974 color->red)</pre>
<pre>Dictionary(name->Rocket Skates price->15.25 year->1974 color->red)</pre>
Line 1,612: Line 1,612:
=={{header|Swift}}==
=={{header|Swift}}==
{{works with|Swift|5+}}
{{works with|Swift|5+}}
<lang swift>let base : [String: Any] = ["name": "Rocket Skates", "price": 12.75, "color": "yellow"]
<syntaxhighlight lang=swift>let base : [String: Any] = ["name": "Rocket Skates", "price": 12.75, "color": "yellow"]
let update : [String: Any] = ["price": 15.25, "color": "red", "year": 1974]
let update : [String: Any] = ["price": 15.25, "color": "red", "year": 1974]


let result = base.merging(update) { (_, new) in new }
let result = base.merging(update) { (_, new) in new }


print(result)</lang>
print(result)</syntaxhighlight>
{{output}}
{{output}}
<pre>["price": 15.25, "name": "Rocket Skates", "color": "red", "year": 1974]</pre>
<pre>["price": 15.25, "name": "Rocket Skates", "color": "red", "year": 1974]</pre>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set dict1 [dict create name "Rocket Skates" price 12.75 color yellow]
<syntaxhighlight lang=tcl>set dict1 [dict create name "Rocket Skates" price 12.75 color yellow]
set dict2 [dict create price 15.25 color red year 1974]
set dict2 [dict create price 15.25 color red year 1974]
dict for {key val} [dict merge $dict1 $dict2] {
dict for {key val} [dict merge $dict1 $dict2] {
puts "$key: $val"
puts "$key: $val"
}</lang>
}</syntaxhighlight>
{{output}}
{{output}}
<pre>name: Rocket Skates
<pre>name: Rocket Skates
Line 1,636: Line 1,636:
3 ways to do this tasks :
3 ways to do this tasks :
First : With Arrays + Type
First : With Arrays + Type
<syntaxhighlight lang=vb>
<lang vb>
Private Type Associative
Private Type Associative
Key As String
Key As String
Line 1,692: Line 1,692:
Next i
Next i
Debug.Print "-----------------------------"
Debug.Print "-----------------------------"
End Sub</lang>
End Sub</syntaxhighlight>


Second way (simply) : with the Scripting Dictionary Object :
Second way (simply) : with the Scripting Dictionary Object :
<lang vb>Sub Main_With_Dictionary()
<syntaxhighlight lang=vb>Sub Main_With_Dictionary()
Dim Base As Object, Update As Object, Merged As Object, K As Variant
Dim Base As Object, Update As Object, Merged As Object, K As Variant
'INIT VARIABLE
'INIT VARIABLE
Line 1,717: Line 1,717:
Debug.Print K, Merged(K)
Debug.Print K, Merged(K)
Next K
Next K
End Sub</lang>
End Sub</syntaxhighlight>


And the Third : With a Class Module (named ClassArrayAssociative)
And the Third : With a Class Module (named ClassArrayAssociative)
The Class Module code:
The Class Module code:
<lang vb>Option Explicit
<syntaxhighlight lang=vb>Option Explicit


Private mKey As String
Private mKey As String
Line 1,742: Line 1,742:
Value = V
Value = V
Key = K
Key = K
End Sub</lang>
End Sub</syntaxhighlight>
The Module code :
The Module code :
<lang vb>Sub Main_With_Class()
<syntaxhighlight lang=vb>Sub Main_With_Class()
Dim Base(2) As New ClassArrayAssociative, Up(2) As New ClassArrayAssociative
Dim Base(2) As New ClassArrayAssociative, Up(2) As New ClassArrayAssociative
ReDim Result(UBound(Base)) As New ClassArrayAssociative
ReDim Result(UBound(Base)) As New ClassArrayAssociative
Line 1,786: Line 1,786:
Next i
Next i
Debug.Print "-----------------------------"
Debug.Print "-----------------------------"
End Sub</lang>
End Sub</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,797: Line 1,797:


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang=vb>
<lang vb>
set d1=createobject("Scripting.Dictionary")
set d1=createobject("Scripting.Dictionary")
d1.add "name", "Rocket Skates"
d1.add "name", "Rocket Skates"
Line 1,827: Line 1,827:
wscript.echo k3 & vbtab & d3(k3)
wscript.echo k3 & vbtab & d3(k3)
next
next
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,837: Line 1,837:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var mergeMaps = Fn.new { |m1, m2|
<syntaxhighlight lang=ecmascript>var mergeMaps = Fn.new { |m1, m2|
var m3 = {}
var m3 = {}
for (key in m1.keys) m3[key] = m1[key]
for (key in m1.keys) m3[key] = m1[key]
Line 1,847: Line 1,847:
var update = { "price": 15.25, "color": "red", "year": 1974 }
var update = { "price": 15.25, "color": "red", "year": 1974 }
var merged = mergeMaps.call(base, update)
var merged = mergeMaps.call(base, update)
System.print(merged)</lang>
System.print(merged)</syntaxhighlight>


{{out}}
{{out}}
Line 1,855: Line 1,855:


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>type Generic = int|string|f64
<syntaxhighlight lang=vlang>type Generic = int|string|f64
type Assoc = map[string]Generic
type Assoc = map[string]Generic


Line 1,876: Line 1,876:
println('$k: $v')
println('$k: $v')
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,886: Line 1,886:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var mergeMaps = Fn.new { |m1, m2|
<syntaxhighlight lang=ecmascript>var mergeMaps = Fn.new { |m1, m2|
var m3 = {}
var m3 = {}
for (key in m1.keys) m3[key] = m1[key]
for (key in m1.keys) m3[key] = m1[key]
Line 1,896: Line 1,896:
var update = { "price": 15.25, "color": "red", "year": 1974 }
var update = { "price": 15.25, "color": "red", "year": 1974 }
var merged = mergeMaps.call(base, update)
var merged = mergeMaps.call(base, update)
System.print(merged)</lang>
System.print(merged)</syntaxhighlight>


{{out}}
{{out}}
Line 1,904: Line 1,904:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>base:=Dictionary(
<syntaxhighlight lang=zkl>base:=Dictionary(
"name", "Rocket Skates",
"name", "Rocket Skates",
"price", 12.75,
"price", 12.75,
Line 1,915: Line 1,915:
update.pump( new:=base.copy() );
update.pump( new:=base.copy() );


new.pump(Void,fcn([(k,v)]){ println("%s\t%s".fmt(k,v)) });</lang>
new.pump(Void,fcn([(k,v)]){ println("%s\t%s".fmt(k,v)) });</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>