Associative array/Merging: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 47:
{{trans|Python}}
 
<syntaxhighlight lang="11l">V base = [‘name’ = ‘Rocket Skates’, ‘price’ = ‘12.75’, ‘color’ = ‘yellow’]
V update = [‘price’ = ‘15.25’, ‘color’ = ‘red’, ‘year’ = ‘1974’]
 
Line 61:
 
=={{header|Ada}}==
<syntaxhighlight lang=Ada"ada">with Ada.Text_Io;
with Ada.Containers.Indefinite_Ordered_Maps;
 
Line 150:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses the associative array implementations in [[ALGOL_68/prelude]].
<syntaxhighlight lang="algol68"># associative array merging #
# the modes allowed as associative array element values - change to suit #
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.
 
<syntaxhighlight lang="applescript">set baseRecord to {|name|:"Rocket Skates", price:12.75, |color|:"yellow"}
set updateRecord to {price:15.25, |color|:"red", |year|:1974}
 
Line 221:
 
{{output}}
<syntaxhighlight lang="applescript">{price:15.25, |color|:"red", |year|:1974, |name|:"Rocket Skates"}</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">details: #[name: "Rocket Skates" price: 12.75 colour: 'yellow]
newDetails: extend details #[price: 15.25 colour: 'red year: 1974]
 
Line 235:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AutoHotkey"autohotkey">merge(base, update){
Merged := {}
for k, v in base
Line 243:
return Merged
}</syntaxhighlight>
Examples:<syntaxhighlight lang=AutoHotkey"autohotkey">base := {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update := {"price":15.25, "color":"red", "year":1974}
Merged := merge(base, update)
Line 255:
 
=={{header|AWK}}==
<syntaxhighlight lang=AWK"awk">
# syntax: GAWK -f ASSOCIATIVE_ARRAY_MERGING.AWK
#
Line 304:
 
=={{header|B4X}}==
<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 merged As Map
Line 316:
 
=={{header|BaCon}}==
<syntaxhighlight lang="bacon">DECLARE base$, update$, merge$ ASSOC STRING
 
base$("name") = "Rocket Skates"
Line 361:
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <map>
Line 399:
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 433:
 
=={{header|Clojure}}==
<syntaxhighlight lang=Clojure"clojure">
(defn update-map [base update]
(merge base update))
Line 451:
 
=={{header|Crystal}}==
<syntaxhighlight lang="crystal">base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
update = { "price" => 15.25, "color" => "red", "year" => 1974 }
 
Line 462:
=={{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:
<syntaxhighlight lang="lisp">
(append list2 list1)
</syntaxhighlight>
 
These implementations for alists and plists are more complicated, but avoid duplicate keys in the results:
<syntaxhighlight lang="lisp">
(defun merge-alists (alist1 alist2)
(nconc
Line 486:
 
=={{header|Dart}}==
<syntaxhighlight lang="javascript">
main() {
var base = {
Line 512:
{{libheader| System.Generics.Collections}}
{{Trans|C#}}
<syntaxhighlight lang=Delphi"delphi">
program Associative_arrayMerging;
 
Line 565:
=={{header|Elixir}}==
Elixir has a built-in hashmap type, called [https://hexdocs.pm/elixir/Map.html Map].
<syntaxhighlight lang=Elixir"elixir">base = %{name: "Rocket Skates", price: 12.75, color: "yellow"}
update = %{price: 15.25, color: "red", year: 1974}
result = Map.merge(base, update)
Line 572:
<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:
<syntaxhighlight lang=Elixir"elixir">base = %{"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
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 593:
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}}
<syntaxhighlight lang="factor">USING: assocs prettyprint ;
 
{ { "name" "Rocket Skates" } { "price" 12.75 } { "color" "yellow" } }
Line 609:
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 641:
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:
<syntaxhighlight lang="haskell">data Item = Item
{ name :: Maybe String
, price :: Maybe Float
Line 662:
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="unicon">procedure main()
local base, update, master, f, k
 
Line 693:
 
=={{header|J}}==
<syntaxhighlight lang=J"j">
merge=: ,. NB. use: update merge original
compress=: #"1~ ~:@:keys
Line 752:
 
=={{header|Java}}==
<syntaxhighlight lang="java">import java.util.*;
 
class MergeMaps {
Line 775:
 
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 845:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">
fun main() {
val base = HashMap<String,String>()
Line 874:
 
=={{header|Lua}}==
<syntaxhighlight lang=Lua"lua">base = {name="Rocket Skates", price=12.75, color="yellow"}
update = {price=15.25, color="red", year=1974}
 
Line 900:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">a1 = <|"name" -> "Rocket Skates", "price" -> 12.75, "color" -> "yellow"|>;
a2 = <|"price" -> 15.25, "color" -> "red", "year" -> 1974|>;
Merge[{a1, a2}, Last]</syntaxhighlight>
Line 908:
=={{header|MiniScript}}==
MiniScript supports merging maps with the + operator.
<syntaxhighlight lang=MiniScript"miniscript">base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
 
Line 919:
 
=={{header|Nim}}==
<syntaxhighlight lang=Nim"nim">import tables
 
let t1 = {"name": "Rocket Skates", "price": "12.75", "color": "yellow"}.toTable
Line 935:
=={{header|Objective-C}}==
{{works with|Cocoa}}
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main(void) {
Line 964:
 
Helper code for all 3 versions:
<syntaxhighlight lang=OCaml"ocaml">
type ty =
| TFloat of float
Line 984:
 
Association list : naive and functional approach.
<syntaxhighlight lang=OCaml"ocaml">
let l1 : assoc list = [
("name", TString "Rocket Skates");
Line 1,011:
Binary tree/Map functor : proper functional approach.
{{works with|OCaml|above 4.03 for union function}}
<syntaxhighlight lang=OCaml"ocaml">
module StringMap = Map.Make(String) ;;
 
Line 1,040:
 
Hash table : imperative/mutable approach.
<syntaxhighlight lang=OCaml"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,066:
Since version 3.1.1 function `ff-union` changed from `(ff-union a1 a2 collide)` to `(ff-union collide a1 a2 ...)`!
 
<syntaxhighlight lang="scheme">
(define a1 {
'name "Rocket Skates"
Line 1,093:
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use strict;
use warnings;
 
Line 1,122:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<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,138:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">include ..\Utilitys.pmt
 
def scand /# dict key -- dict n #/
Line 1,187:
 
=={{header|PHP}}==
<syntaxhighlight lang="php"><?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
Line 1,204:
 
Alternative:
<syntaxhighlight lang="php"><?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
Line 1,221:
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">NewMap m1.s()
NewMap m2.s()
NewMap m3.s()
Line 1,251:
As of Python 3.5, this can be solved with the dictionary unpacking operator.
{{works with|Python|3.5+}}
<syntaxhighlight lang=Python"python">base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
 
Line 1,261:
 
;Alternative:
<syntaxhighlight lang=Python"python">base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
 
Line 1,273:
;New alternative using '|'
 
<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.
>>> base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
Line 1,284:
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">#lang racket/base
 
(require racket/hash)
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.
 
<syntaxhighlight lang=perl6"raku" line># Show original hashes
say my %base = :name('Rocket Skates'), :price<12.75>, :color<yellow>;
say my %update = :price<15.25>, :color<red>, :year<1974>;
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,
<br>although they could easily be added.
<syntaxhighlight lang="rexx">/*REXX program merges two associative arrays (requiring an external list of indices). */
$.= /*define default value(s) for arrays. */
@.wAAn= 21; @.wKey= 7; @.wVal= 7 /*max widths of: AAname, keys, values.*/
Line 1,418:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 1,452:
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
update = {"price" => 15.25, "color" => "red", "year" => 1974}
 
Line 1,461:
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::collections::HashMap;
 
fn main() {
Line 1,493:
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.
<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.)
(define append-alists
Line 1,528:
This is more true to the intent of the Task. It generates a new alist with only the key/value
pairs needed.
<syntaxhighlight lang="scheme">; Merge the given alists. Prefer the items from the "update" alist.
; Returns a new list; the argument lists are not modified.
(define merge-alists
Line 1,569:
=={{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.
<syntaxhighlight lang="sensetalk">set base to {name:"Rocket Skates", price:12.75, color:"yellow"}
 
set update to {price:15.25, color:"red", year:1974}
Line 1,592:
 
=={{header|Smalltalk}}==
<syntaxhighlight lang="smalltalk">base := Dictionary withAssociations:{
'name'-> 'Rocket Skates' .
'price' -> 12.75 .
Line 1,612:
=={{header|Swift}}==
{{works with|Swift|5+}}
<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]
 
Line 1,622:
 
=={{header|Tcl}}==
<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]
dict for {key val} [dict merge $dict1 $dict2] {
Line 1,636:
3 ways to do this tasks :
First : With Arrays + Type
<syntaxhighlight lang="vb">
Private Type Associative
Key As String
Line 1,695:
 
Second way (simply) : with the Scripting Dictionary Object :
<syntaxhighlight lang="vb">Sub Main_With_Dictionary()
Dim Base As Object, Update As Object, Merged As Object, K As Variant
'INIT VARIABLE
Line 1,721:
And the Third : With a Class Module (named ClassArrayAssociative)
The Class Module code:
<syntaxhighlight lang="vb">Option Explicit
 
Private mKey As String
Line 1,744:
End Sub</syntaxhighlight>
The Module code :
<syntaxhighlight lang="vb">Sub Main_With_Class()
Dim Base(2) As New ClassArrayAssociative, Up(2) As New ClassArrayAssociative
ReDim Result(UBound(Base)) As New ClassArrayAssociative
Line 1,797:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
set d1=createobject("Scripting.Dictionary")
d1.add "name", "Rocket Skates"
Line 1,837:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascript">var mergeMaps = Fn.new { |m1, m2|
var m3 = {}
for (key in m1.keys) m3[key] = m1[key]
Line 1,855:
 
=={{header|Vlang}}==
<syntaxhighlight lang="vlang">type Generic = int|string|f64
type Assoc = map[string]Generic
 
Line 1,886:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascript">var mergeMaps = Fn.new { |m1, m2|
var m3 = {}
for (key in m1.keys) m3[key] = m1[key]
Line 1,904:
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">base:=Dictionary(
"name", "Rocket Skates",
"price", 12.75,
10,333

edits