Associative array/Merging: Difference between revisions
m
Moved Vlang entry into correct alphabetical order.
m (Moved Vlang entry into correct alphabetical order.) |
|||
(8 intermediate revisions by 6 users not shown) | |||
Line 47:
{{trans|Python}}
<
V update = [‘price’ = ‘15.25’, ‘color’ = ‘red’, ‘year’ = ‘1974’]
Line 53:
result.update(update)
print(result)</
{{out}}
Line 61:
=={{header|Ada}}==
<
with Ada.Containers.Indefinite_Ordered_Maps;
Line 129:
New_Line;
end Merge_Maps;</
{{out}}
<pre>Original:
Line 150:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses the associative array implementations in [[ALGOL_68/prelude]].
<
# the modes allowed as associative array element values - change to suit #
Line 201:
);
e := NEXT c
OD</
{{out}}
<pre>
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.
<
set updateRecord to {price:15.25, |color|:"red", |year|:1974}
set mergedRecord to updateRecord & baseRecord
return mergedRecord</
{{output}}
<
=={{header|Arturo}}==
<
newDetails: extend details #[price: 15.25 colour: 'red year: 1974]
print newDetails</
{{out}}
Line 235:
=={{header|AutoHotkey}}==
<
Merged := {}
for k, v in base
Line 242:
Merged[k] := v
return Merged
}</
Examples:<
update := {"price":15.25, "color":"red", "year":1974}
Merged := merge(base, update)
for k, v in Merged
result .= k " : " v "`n"
MsgBox % result</
Outputs:<pre>color : red
name : Rocket Skates
Line 255:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f ASSOCIATIVE_ARRAY_MERGING.AWK
#
Line 283:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 304:
=={{header|B4X}}==
<
Dim m2 As Map = CreateMap("price": 15.25, "color": "red", "year": 1974)
Dim merged As Map
Line 313:
Next
Next
Log(merged)</
=={{header|
==={{header|BaCon}}===
<syntaxhighlight lang="bacon">DECLARE base$, update$, merge$ ASSOC STRING
base$("name") = "Rocket Skates"
Line 342 ⟶ 343:
FOR x$ IN OBTAIN$(merge$)
PRINT x$, " : ", merge$(x$)
NEXT</
{{out}}
<pre>Base array
Line 361 ⟶ 362:
=={{header|C++}}==
<
#include <string>
#include <map>
Line 388 ⟶ 389:
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 0;
}</
{{out}}
Line 399 ⟶ 400:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 424 ⟶ 425:
}
}
}</
{{out}}
<pre>
Line 433 ⟶ 434:
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(defn update-map [base update]
(merge base update))
Line 443 ⟶ 444:
"color" "red"
"year" "1974"})
</syntaxhighlight>
{{out}}
Line 451 ⟶ 452:
=={{header|Crystal}}==
<
update = { "price" => 15.25, "color" => "red", "year" => 1974 }
puts base.merge(update)</
{{out}}
Line 462 ⟶ 463:
=={{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:
<
(append list2 list1)
</syntaxhighlight>
These implementations for alists and plists are more complicated, but avoid duplicate keys in the results:
<
(defun merge-alists (alist1 alist2)
(nconc
Line 483 ⟶ 484:
:do (setf (getf res key) val))
res))
</syntaxhighlight>
=={{header|Dart}}==
<
main() {
var base = {
Line 508 ⟶ 509:
}
</syntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.Generics.Collections}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Associative_arrayMerging;
Line 555 ⟶ 556:
end.
</syntaxhighlight>
{{out}}
<pre>
Line 565 ⟶ 566:
=={{header|Elixir}}==
Elixir has a built-in hashmap type, called [https://hexdocs.pm/elixir/Map.html Map].
<
update = %{price: 15.25, color: "red", year: 1974}
result = Map.merge(base, update)
IO.inspect(result)</
{{out}}
<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:
<
=={{header|F_Sharp|F#}}==
<
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"))]
Line 581 ⟶ 582:
let ng=(Map.toList n)@(Map.toList g)|>Map.ofList
printfn "%A" ng
</syntaxhighlight>
{{out}}
<pre>
Line 593 ⟶ 594:
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}}
<
{ { "name" "Rocket Skates" } { "price" 12.75 } { "color" "yellow" } }
{ { "price" 15.25 } { "color" "red" } { "year" 1974 } }
assoc-union .</
{{out}}
<pre>
Line 607 ⟶ 608:
}
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
void local fn DoIt
CFDictionaryRef base = @{@"name" :@"Rocket Skates", @"price":@12.75, @"color":@"yellow"}
CFDictionaryRef update = @{@"price":@15.25, @"color":@"red", @"year":@1974}
CFMutableDictionaryRef merged = fn MutableDictionaryWithDictionary( base )
MutableDictionaryAddEntriesFromDictionary( merged, update )
print merged
end fn
fn DoIt
HandleEvents
</syntaxhighlight>
=={{header|Go}}==
<
import "fmt"
Line 631 ⟶ 650:
result := merge(base, update)
fmt.Println(result)
}</
{{out}}
Line 641 ⟶ 660:
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:
<
{ name :: Maybe String
, price :: Maybe Float
Line 657 ⟶ 676:
itemFromMerge
(Item (Just "Rocket Skates") (Just 12.75) (Just "yellow") Nothing)
(Item Nothing (Just 15.25) (Just "red") (Just 1974))</
{{Out}}
<pre>Item {name = Just "Rocket Skates", price = Just 15.25, color = Just "red", year = Just 1974}</pre>
=={{header|Icon}} and {{header|Unicon}}==
<
local base, update, master, f, k
Line 683 ⟶ 702:
write(k, " = ", master[k])
}
end</
{{out}}
Line 693 ⟶ 712:
=={{header|J}}==
<syntaxhighlight lang="j">
merge=: ,. NB. use: update merge original
compress=: #"1~ ~:@:keys
Line 700 ⟶ 719:
get=: [: > ((i.~ keys)~ <)~ { values@:] NB. key get (associative array)
pair=: [: |: <;._2;._2
</syntaxhighlight>
Exercise the definitions. Interactive J prompts with 3 space indentation.
<pre>
Line 752 ⟶ 771:
=={{header|Java}}==
<p>
See also, [https://rosettacode.org/wiki/Associative_array/Creation#Java Java - Associative array/Creation].
</p>
<p>
This task illustrates the difference between statically typed languages, and dynamically typed.<br />
With exception to the <code>var</code> keyword, Java is statically typed.
So, using an undefined, non-static, <kbd>value</kbd>, creates a trivial situation.
</p>
<p>
A good way to understand this task is that it's not possible in a static-typed language.<br />
It defeats the purpose of defining the data-type.<br />
For Java, if you're going to use <code>Object</code> as your data-type, you need to re-evaluate the method of abstraction.
</p>
<p>
Java offers <kbd>generics</kbd>, <kbd>interfaces</kbd>, and <kbd>abstract classes</kbd> for this task.
</p>
<p>
Considering this, to complete this specific task, I would just store the values as <kbd>strings</kbd>.
</p>
<syntaxhighlight lang="java">
import java.util.LinkedHashMap;
import java.util.Map;
</syntaxhighlight>
<syntaxhighlight lang="java">
Map<String, String> mapA = new LinkedHashMap<>();
mapA.put("name", "Rocket Skates");
mapA.put("price", "12.75");
mapA.put("color", "yellow");
Map<String, String> mapB = new LinkedHashMap<>();
mapB.put("price", "15.25");
mapB.put("color", "red");
mapC.putAll(mapB);
</syntaxhighlight>
To show that the original <kbd>map</kbd>s are not affected.
<syntaxhighlight lang="java">
for(Map.Entry<String, String> entry : mapA.entrySet())
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
for(Map.Entry<String, String> entry : mapB.entrySet())
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
for(Map.Entry<String, String> entry : mapC.entrySet())
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
</syntaxhighlight>
<pre>
name Rocket Skates
price 12.75
color yellow
</pre>
<pre>
price 15.25
color red
year 1974
</pre>
<pre>
name Rocket Skates
price 15.25
color red
year 1974
</pre>
<p>
While not recommended, due to scalability, if you did want to use an <code>Object</code> as the value, you could use the following implementation.<br />
This will produce the same output as above.
</p>
<syntaxhighlight lang="java">
Map<String, Object> mapA = new LinkedHashMap<>();
mapA.put("name", "Rocket Skates");
mapA.put("price", 12.75);
mapA.put("color", "yellow");
Map<String, Object> mapB = new LinkedHashMap<>();
mapB.put("price", 15.25);
mapB.put("color", "red");
mapB.put("year", 1974);
Map<String, Object> mapC = new LinkedHashMap<>();
mapC.putAll(mapA);
mapC.putAll(mapB);
</syntaxhighlight>
=={{header|JavaScript}}==
<
'use strict';
Line 792 ⟶ 874:
null, 2
))
})();</
{{Out}}
<pre>{
Line 845 ⟶ 927:
=={{header|Kotlin}}==
<
fun main() {
val base = HashMap<String,String>()
Line 865 ⟶ 947:
println("merged: $merged")
}
</syntaxhighlight>
{{Output}}
<pre>
Line 874 ⟶ 956:
=={{header|Lua}}==
<
update = {price=15.25, color="red", year=1974}
Line 891 ⟶ 973:
for key,val in pairs(result) do
print(string.format("%s: %s", key, val))
end</
{{output}}
Line 900 ⟶ 982:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
a2 = <|"price" -> 15.25, "color" -> "red", "year" -> 1974|>;
Merge[{a1, a2}, Last]</
{{out}}
<pre><|"name" -> "Rocket Skates", "price" -> 15.25, "color" -> "red", "year" -> 1974|></pre>
Line 908 ⟶ 990:
=={{header|MiniScript}}==
MiniScript supports merging maps with the + operator.
<
update = {"price":15.25, "color":"red", "year":1974}
result = base + update
print result</
{{output}}
Line 919 ⟶ 1,001:
=={{header|Nim}}==
<
let t1 = {"name": "Rocket Skates", "price": "12.75", "color": "yellow"}.toTable
Line 928 ⟶ 1,010:
t3[key] = value
echo t3</
{{out}}
Line 935 ⟶ 1,017:
=={{header|Objective-C}}==
{{works with|Cocoa}}
<
int main(void) {
Line 948 ⟶ 1,030:
}
return 0;
}</
{{output}}
<pre>{
Line 964 ⟶ 1,046:
Helper code for all 3 versions:
<syntaxhighlight lang="ocaml">
type ty =
| TFloat of float
Line 981 ⟶ 1,063:
Printf.printf "%s: %s\n" key (string_of_ty el)
;;
</syntaxhighlight>
Association list : naive and functional approach.
<syntaxhighlight lang="ocaml">
let l1 : assoc list = [
("name", TString "Rocket Skates");
Line 1,007 ⟶ 1,089:
let l' = merge_assoc_list l1 l2 ;;
</syntaxhighlight>
Binary tree/Map functor : proper functional approach.
{{works with|OCaml|above 4.03 for union function}}
<syntaxhighlight lang="ocaml">
module StringMap = Map.Make(String) ;;
Line 1,037 ⟶ 1,119:
print_map m' ;;
</syntaxhighlight>
Hash table : imperative/mutable approach.
<syntaxhighlight lang="ocaml">
(* Updates the base table with the bindings from add *)
let hash_merge (base : (string, ty) Hashtbl.t) (add : (string, ty) Hashtbl.t) : unit =
Line 1,061 ⟶ 1,143:
print_hashtbl h1 ;;
</syntaxhighlight>
=={{header|Ol}}==
Since version 3.1.1 function `ff-union` changed from `(ff-union a1 a2 collide)` to `(ff-union collide a1 a2 ...)`!
<
(define a1 {
'name "Rocket Skates"
Line 1,084 ⟶ 1,166:
(define (collide a b) b) ; will use new key value
(print "merged a1 a2: " (ff-union collide a1 a2))
</syntaxhighlight>
{{Out}}
<pre>
Line 1,093 ⟶ 1,175:
=={{header|Perl}}==
<
use warnings;
Line 1,107 ⟶ 1,189:
$merge{$_} = [$base{$_}] for keys %base;
push @{$merge{$_}}, $more{$_} for keys %more;
printf "%-7s %s\n", $_, join ', ', @{$merge{$_}} for sort keys %merge;</
{{output}}
<pre>Update
Line 1,122 ⟶ 1,204:
=={{header|Phix}}==
<!--<
<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>
Line 1,131 ⟶ 1,213:
<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>
<!--</
{{out}}
<pre>
Line 1,138 ⟶ 1,220:
=={{header|Phixmonti}}==
<
def scand /# dict key -- dict n #/
Line 1,184 ⟶ 1,266:
pstack
</syntaxhighlight>
=={{header|PHP}}==
<
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
Line 1,193 ⟶ 1,275:
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?></
{{output}}
<pre>Array
Line 1,204 ⟶ 1,286:
Alternative:
<
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
Line 1,210 ⟶ 1,292:
$result = array_merge($base, $update);
print_r($result);
?></
{{output}}
<pre>Array
Line 1,221 ⟶ 1,303:
=={{header|PureBasic}}==
<
NewMap m2.s()
NewMap m3.s()
Line 1,241 ⟶ 1,323:
ForEach m3()
Debug MapKey(m3())+" : "+m3()
Next</
{{out}}
<pre>price : 15.25
Line 1,251 ⟶ 1,333:
As of Python 3.5, this can be solved with the dictionary unpacking operator.
{{works with|Python|3.5+}}
<
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)</
{{output}}
<pre>{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}</pre>
;Alternative:
<
update = {"price":15.25, "color":"red", "year":1974}
Line 1,267 ⟶ 1,349:
result.update(update)
print(result)</
{{output}}
<pre>{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}</pre>
Line 1,273 ⟶ 1,355:
;New alternative using '|'
<
Type "help", "copyright", "credits" or "license()" for more information.
>>> base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
Line 1,280 ⟶ 1,362:
>>> result
{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}
>>> </
=={{header|Racket}}==
<
(require racket/hash)
Line 1,300 ⟶ 1,382:
(hash-union base-data update-data #:combine (λ (a b) b)))
</syntaxhighlight>
{{out}}
Line 1,310 ⟶ 1,392:
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.
<syntaxhighlight lang="raku"
say my %base = :name('Rocket Skates'), :price<12.75>, :color<yellow>;
say my %update = :price<15.25>, :color<red>, :year<1974>;
Line 1,325 ⟶ 1,407:
# Demonstrate unmutated hashes
say "\n", %base, "\n", %update;</
{{out}}
<pre>{color => yellow, name => Rocket Skates, price => 12.75}
Line 1,365 ⟶ 1,447:
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.
<
$.= /*define default value(s) for arrays. */
@.wAAn= 21; @.wKey= 7; @.wVal= 7 /*max widths of: AAname, keys, values.*/
Line 1,397 ⟶ 1,479:
say center(AAn, @.wAAn) right(key, @.wKey) $.AAn.key /*show some information.*/
end /*j*/
return</
{{out|output|text= when using the internal default inputs:}}
<pre>
Line 1,418 ⟶ 1,500:
=={{header|Ring}}==
<
load "stdlib.ring"
Line 1,442 ⟶ 1,524:
see list1[n][1] + " = " + list1[n][2] + nl
next
</syntaxhighlight>
Output:
<pre>
Line 1,452 ⟶ 1,534:
=={{header|Ruby}}==
<
update = {"price" => 15.25, "color" => "red", "year" => 1974}
result = base.merge(update)
p result</
{{output}}
<pre>{"name"=>"Rocket Skates", "price"=>15.25, "color"=>"red", "year"=>1974}</pre>
=={{header|Rust}}==
<
fn main() {
Line 1,478 ⟶ 1,560:
println!("{:#?}", original);
}
</syntaxhighlight>
{{output}}
<pre>{
Line 1,493 ⟶ 1,575:
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.
<
; (The extra '() is so that append doesn't co-opt the second list.)
(define append-alists
Line 1,512 ⟶ 1,594:
(unless (null? keys)
(printf "~s -> ~s~%" (car keys) (cdr (assoc (car keys) merged)))
(loop (cdr keys))))))</
{{out}}
<pre>
Line 1,528 ⟶ 1,610:
This is more true to the intent of the Task. It generates a new alist with only the key/value
pairs needed.
<
; Returns a new list; the argument lists are not modified.
(define merge-alists
Line 1,554 ⟶ 1,636:
(unless (null? keys)
(printf "~s -> ~s~%" (car keys) (cdr (assoc (car keys) merged)))
(loop (cdr keys))))))</
{{out}}
<pre>
Line 1,569 ⟶ 1,651:
=={{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.
<
set update to {price:15.25, color:"red", year:1974}
Line 1,582 ⟶ 1,664:
replace properties of update in base
put "Base after update: " & base
</syntaxhighlight>
{{out}}
<pre>
Line 1,592 ⟶ 1,674:
=={{header|Smalltalk}}==
<
'name'-> 'Rocket Skates' .
'price' -> 12.75 .
Line 1,606 ⟶ 1,688:
declareAllFrom:update.
Transcript showCR: result.</
{{out}}
<pre>Dictionary(name->Rocket Skates price->15.25 year->1974 color->red)</pre>
Line 1,612 ⟶ 1,694:
=={{header|Swift}}==
{{works with|Swift|5+}}
<
let update : [String: Any] = ["price": 15.25, "color": "red", "year": 1974]
let result = base.merging(update) { (_, new) in new }
print(result)</
{{output}}
<pre>["price": 15.25, "name": "Rocket Skates", "color": "red", "year": 1974]</pre>
=={{header|Tcl}}==
<
set dict2 [dict create price 15.25 color red year 1974]
dict for {key val} [dict merge $dict1 $dict2] {
puts "$key: $val"
}</
{{output}}
<pre>name: Rocket Skates
Line 1,636 ⟶ 1,718:
3 ways to do this tasks :
First : With Arrays + Type
<syntaxhighlight lang="vb">
Private Type Associative
Key As String
Line 1,692 ⟶ 1,774:
Next i
Debug.Print "-----------------------------"
End Sub</
Second way (simply) : with the Scripting Dictionary Object :
<
Dim Base As Object, Update As Object, Merged As Object, K As Variant
'INIT VARIABLE
Line 1,717 ⟶ 1,799:
Debug.Print K, Merged(K)
Next K
End Sub</
And the Third : With a Class Module (named ClassArrayAssociative)
The Class Module code:
<
Private mKey As String
Line 1,742 ⟶ 1,824:
Value = V
Key = K
End Sub</
The Module code :
<
Dim Base(2) As New ClassArrayAssociative, Up(2) As New ClassArrayAssociative
ReDim Result(UBound(Base)) As New ClassArrayAssociative
Line 1,786 ⟶ 1,868:
Next i
Debug.Print "-----------------------------"
End Sub</
{{out}}
<pre>
Line 1,797 ⟶ 1,879:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
set d1=createobject("Scripting.Dictionary")
d1.add "name", "Rocket Skates"
Line 1,827 ⟶ 1,909:
wscript.echo k3 & vbtab & d3(k3)
next
</syntaxhighlight>
{{out}}
<pre>
Line 1,836 ⟶ 1,918:
</pre>
=={{header|
<syntaxhighlight lang="v (vlang)">type Generic = int|string|f64
type Assoc = map[string]Generic
Line 1,876 ⟶ 1,940:
println('$k: $v')
}
}</
{{out}}
<pre>
Line 1,886 ⟶ 1,950:
=={{header|Wren}}==
<
var m3 = {}
for (key in m1.keys) m3[key] = m1[key]
Line 1,896 ⟶ 1,960:
var update = { "price": 15.25, "color": "red", "year": 1974 }
var merged = mergeMaps.call(base, update)
System.print(merged)</
{{out}}
Line 1,904 ⟶ 1,968:
=={{header|zkl}}==
<
"name", "Rocket Skates",
"price", 12.75,
Line 1,915 ⟶ 1,979:
update.pump( new:=base.copy() );
new.pump(Void,fcn([(k,v)]){ println("%s\t%s".fmt(k,v)) });</
{{out}}
<pre>
|