import ceylon.collection {

	ArrayList,
	HashMap,
	naturalOrderTreeMap
}

shared void run() {

	// the easiest way is to use the map function to create
	// an immutable map
	value myMap = map {
		"foo" -> 5,
		"bar" -> 10,
		"baz" -> 15,
		"foo" -> 6 // by default the first "foo" will remain
	};

	// or you can use the HashMap constructor to create
	// a mutable one
	value myOtherMap = HashMap {
		"foo"->"bar"
	};
	myOtherMap.put("baz", "baxx");

	// there's also a sorted red/black tree map
	value myTreeMap = naturalOrderTreeMap {
		1 -> "won",
		2 -> "too",
		4 -> "fore"
	};
	for(num->homophone in myTreeMap) {
		print("``num`` is ``homophone``");
	}

}


// arr is an array of string to int. any type can be used in both places.
var keys: domain(string);
var arr: [keys] int;

// keys can be added to a domain using +, new values will be initialized to the default value (0 for int)
keys += "foo";
keys += "bar";
keys += "baz";

// array access via [] or ()
arr["foo"] = 1;
arr["bar"] = 4;
arr("baz") = 6;

// write auto-formats domains and arrays
writeln("Keys: ", keys);
writeln("Values: ", arr);

// keys can be deleted using -
keys -= "bar";

writeln("Keys: ", keys);
writeln("Values: ", arr);

// chapel also supports array literals
var arr2 = [ "John" => 3, "Pete" => 14 ];

writeln("arr2 keys: ", arr2.domain);
writeln("arr2 values: ", arr2);


{:key "value"
 :key2 "value2"
 :key3 "value3"}


<cfset myHash = structNew()>
<cfset myHash.key1 = "foo">
<cfset myHash["key2"] = "bar">
<cfset myHash.put("key3","java-style")>


;; default :test is #'eql, which is suitable for numbers only,
;; or for implementation identity for other types!
;; Use #'equalp if you want case-insensitive keying on strings.

(setf my-hash (make-hash-table :test #'equal))
(setf (gethash "H2O" my-hash) "Water")
(setf (gethash "HCl" my-hash) "Hydrochloric Acid")
(setf (gethash "CO" my-hash) "Carbon Monoxide")

;; That was actually a hash table, an associative array or
;; alist is written like this:
(defparameter *legs* '((cow . 4) (flamingo . 2) (centipede . 100)))
;; you can use assoc to do lookups and cons new elements onto it to make it longer.


DEFINITION Collections;

	IMPORT Boxes;

	CONST
		notFound = -1;

	TYPE
		Hash = POINTER TO RECORD
			cap-, size-: INTEGER;
			(h: Hash) ContainsKey (k: Boxes.Object): BOOLEAN, NEW;
			(h: Hash) Get (k: Boxes.Object): Boxes.Object, NEW;
			(h: Hash) IsEmpty (): BOOLEAN, NEW;
			(h: Hash) Put (k, v: Boxes.Object): Boxes.Object, NEW;
			(h: Hash) Remove (k: Boxes.Object): Boxes.Object, NEW;
			(h: Hash) Reset, NEW
		END;

		HashMap = POINTER TO RECORD
			cap-, size-: INTEGER;
			(hm: HashMap) ContainsKey (k: Boxes.Object): BOOLEAN, NEW;
			(hm: HashMap) ContainsValue (v: Boxes.Object): BOOLEAN, NEW;
			(hm: HashMap) Get (k: Boxes.Object): Boxes.Object, NEW;
			(hm: HashMap) IsEmpty (): BOOLEAN, NEW;
			(hm: HashMap) Keys (): POINTER TO ARRAY OF Boxes.Object, NEW;
			(hm: HashMap) Put (k, v: Boxes.Object): Boxes.Object, NEW;
			(hm: HashMap) Remove (k: Boxes.Object): Boxes.Object, NEW;
			(hm: HashMap) Reset, NEW;
			(hm: HashMap) Values (): POINTER TO ARRAY OF Boxes.Object, NEW
		END;

		LinkedList = POINTER TO RECORD
			first-, last-: Node;
			size-: INTEGER;
			(ll: LinkedList) Add (item: Boxes.Object), NEW;
			(ll: LinkedList) Append (item: Boxes.Object), NEW;
			(ll: LinkedList) AsString (): POINTER TO ARRAY OF CHAR, NEW;
			(ll: LinkedList) Contains (item: Boxes.Object): BOOLEAN, NEW;
			(ll: LinkedList) Get (at: INTEGER): Boxes.Object, NEW;
			(ll: LinkedList) IndexOf (item: Boxes.Object): INTEGER, NEW;
			(ll: LinkedList) Insert (at: INTEGER; item: Boxes.Object), NEW;
			(ll: LinkedList) IsEmpty (): BOOLEAN, NEW;
			(ll: LinkedList) Remove (item: Boxes.Object), NEW;
			(ll: LinkedList) RemoveAt (at: INTEGER), NEW;
			(ll: LinkedList) Reset, NEW;
			(ll: LinkedList) Set (at: INTEGER; item: Boxes.Object), NEW
		END;

		Vector = POINTER TO RECORD
			size-, cap-: LONGINT;
			(v: Vector) Add (item: Boxes.Object), NEW;
			(v: Vector) AddAt (item: Boxes.Object; i: INTEGER), NEW;
			(v: Vector) Contains (o: Boxes.Object): BOOLEAN, NEW;
			(v: Vector) Get (i: LONGINT): Boxes.Object, NEW;
			(v: Vector) IndexOf (o: Boxes.Object): LONGINT, NEW;
			(v: Vector) Remove (o: Boxes.Object), NEW;
			(v: Vector) RemoveIndex (i: LONGINT): Boxes.Object, NEW;
			(v: Vector) Set (i: LONGINT; o: Boxes.Object): Boxes.Object, NEW;
			(v: Vector) Trim, NEW
		END;

	PROCEDURE NewHash (cap: INTEGER): Hash;
	PROCEDURE NewHashMap (cap: INTEGER): HashMap;
	PROCEDURE NewLinkedList (): LinkedList;
	PROCEDURE NewVector (cap: INTEGER): Vector;

END Collections.


hash1 = {"foo" => "bar"}

# hash literals that don't perfectly match the intended hash type must be given an explicit type specification
# the following would fail without `of String => String|Int32`
hash2 : Hash(String, String|Int32) = {"foo" => "bar"} of String => String|Int32


void main() {
    auto hash = ["foo":42, "bar":100];
    assert("foo" in hash);
}


m = { => } # empty ordered map, future inserted keys will be ordered
h = { -> } # empty hash map, future inserted keys will not be ordered

m = { 'foo' => 42, 'bar' => 100 } # with ordered keys
h = { 'foo' -> 42, 'bar' -> 100 } # with unordered keys


main() {
	var rosettaCode = { // Type is inferred to be Map<String, String>
		'task': 'Associative Array Creation'
	};

	rosettaCode['language'] = 'Dart';

	// The update function can be used to update a key using a callback
	rosettaCode.update( 'is fun',  // Key to update
		(value) => "i don't know", // New value to use if key is present
		ifAbsent: () => 'yes!' // Value to use if key is absent
	);

	assert( rosettaCode.toString() == '{task: Associative Array Creation, language: Dart, is fun: yes!}');

	// If we type the Map with dynamic keys and values, it is like a JavaScript object
	Map<dynamic, dynamic> jsObject = {
		'key': 'value',
		1: 2,
		1.5: [ 'more', 'stuff' ],
		#doStuff: () => print('doing stuff!') // #doStuff is a symbol, only one instance of this exists in the program. Would be :doStuff in Ruby
	};

	print( jsObject['key'] );
	print( jsObject[1] );

	for ( var value in jsObject[1.5] )
		print('item: $value');

	jsObject[ #doStuff ](); // Calling the function

	print('\nKey types:');
	jsObject.keys.forEach( (key) => print( key.runtimeType ) );
}


program AssociativeArrayCreation;

{$APPTYPE CONSOLE}

uses Generics.Collections;

var
  lDictionary: TDictionary<string, Integer>;
begin
  lDictionary := TDictionary<string, Integer>.Create;
  try
    lDictionary.Add('foo', 5);
    lDictionary.Add('bar', 10);
    lDictionary.Add('baz', 15);
    lDictionary.AddOrSetValue('foo', 6); // replaces value if it exists
  finally
    lDictionary.Free;
  end;
end.


var t = (x: 1, y: 2, z: 3)
print(t.Keys().ToArray())


[].asMap()                             # immutable, empty
["one" => 1, "two" => 2]               # immutable, 2 mappings
[].asMap().diverge()                   # mutable, empty
["one" => 2].diverge(String, float64)  # mutable, initial contents,
                                        #   typed (coerces to float)


(lib 'hash) ;; needs hash.lib
(define H (make-hash)) ;; new hash table
;; keys may be symbols, numbers, strings ..
;; values may be any lisp object
(hash-set H 'simon 'antoniette)
   → antoniette
(hash-set H 'antoinette 'albert)
   → albert
(hash-set H "Elvis" 42)
    → 42
(hash-ref H 'Elvis)
    → #f ;; not found. Elvis is not "Elvis"
(hash-ref H "Elvis")
    → 42
(hash-ref H 'simon)
    → antoniette
(hash-count H)
    → 3


import system'collections;

public program()
{
    // 1. Create
    var map := Dictionary.new();
    map["key"] := "foox";
    map["key"] := "foo";
    map["key2"]:= "foo2";
    map["key3"]:= "foo3";
    map["key4"]:= "foo4";
}


defmodule RC do
  def test_create do
    IO.puts "< create Map.new >"
    m = Map.new                   #=> creates an empty Map
    m1 = Map.put(m,:foo,1)
    m2 = Map.put(m1,:bar,2)
    print_vals(m2)
    print_vals(%{m2 | foo: 3})
  end

  defp print_vals(m) do
    IO.inspect m
    Enum.each(m, fn {k,v} -> IO.puts "#{inspect k} => #{v}" end)
  end
end

RC.test_create


(setq my-table (make-hash-table))
(puthash 'key 'value my-table)


-module(assoc).
-compile([export_all]).

test_create() ->
    D = dict:new(),
    D1 = dict:store(foo,1,D),
    D2 = dict:store(bar,2,D1),
    print_vals(D2),
    print_vals(dict:store(foo,3,D2)).

print_vals(D) ->
    lists:foreach(fun (K) ->
                          io:format("~p: ~b~n",[K,dict:fetch(K,D)])
                  end, dict:fetch_keys(D)).


let dic = System.Collections.Generic.Dictionary<string,string>() ;;
dic.Add("key","val") ;
dic.["key"] <- "new val" ;


H{ { "one" 1 } { "two" 2 } }
{ [ "one" swap at . ]
  [ 2 swap value-at . ]
  [ "three" swap at . ]
  [ [ 3 "three" ] dip set-at ]
  [ "three" swap at . ] } cleave


class Main
{
  public static Void main ()
  {
    // create a map which maps Ints to Strs, with given key-value pairs
    Int:Str map := [1:"alpha", 2:"beta", 3:"gamma"]

    // create an empty map
    Map map2 := [:]
    // now add some numbers mapped to their doubles
    10.times |Int i|
    {
      map2[i] = 2*i
    }

  }
}


: get ( key len table -- data )     \ 0 if not present
  search-wordlist if
    >body @
  else 0 then ;

: put ( data key len table -- )
  >r 2dup [email protected] search-wordlist if
    r> drop nip nip
    >body !
  else
    r> get-current >r set-current      \ switch definition word lists
    nextname create ,
    r> set-current
  then ;
 wordlist constant bar
5 s" alpha" bar put
9 s" beta"  bar put
2 s" gamma" bar put
s" alpha" bar get .    \ 5
8 s" Alpha" bar put    \ Forth dictionaries are normally case-insensitive
s" alpha" bar get .   \ 8


#define max(a, b) Iif(a>b,a,b)

enum datatype
    'for this demonstration we'll allow these five data types
    BOOL
    STRNG
    BYYTE
    INTEG
    FLOAT
end enum

union value
    bool as boolean
    strng as string*32
    byyte as byte
    integ as integer
    float as double
end union

type dicitem
    'one part of the dictionary entry, either the key or the value
    datatype as datatype   'need to keep track of what kind of data it is
    value as value
end type

type dicentry
    'a dic entry has two things, a key and a value
    key as dicitem
    value as dicitem
end type

sub add_dicentry( Dic() as dicentry, entry as dicentry )
    redim preserve Dic(0 to max(ubound(Dic)+1,0))
    Dic(ubound(Dic)) = entry
    return
end sub

redim as dicentry Dictionary(-1)  'initialise a dictionary with no entries as yet

dim as dicentry thing1, thing2

'generate some test dictionary entries
with thing1
    with .key
        .datatype = STRNG
        .value.strng = "Cat"
    end with
    with .value
        .datatype = STRNG
        .value.strng = "Mittens"
    end with
end with

with thing2
    with .key
        .datatype = integ
        .value.integ = 32767
    end with
    with .value
        .datatype = float
        .value.float = 2.718281828
    end with
end with

add_dicentry( Dictionary(), thing1 )
add_dicentry( Dictionary(), thing2 )

print Dictionary(0).value.value.strng
print Dictionary(1).key.value.integ


program AssociativeArrayCreation;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}
uses Generics.Collections;
var
  lDictionary: TDictionary<string, Integer>;
begin
  lDictionary := TDictionary<string, Integer>.Create;
  try
    lDictionary.Add('foo', 5);
    lDictionary.Add('bar', 10);
    lDictionary.Add('baz', 15);
    lDictionary.AddOrSetValue('foo', 6); // replaces value if it exists
  finally
    lDictionary.Free;
  end;
end.


// declare a nil map variable, for maps from string to int
var x map[string]int

// make an empty map
x = make(map[string]int)

// make an empty map with an initial capacity
x = make(map[string]int, 42)

// set a value
x["foo"] = 3

// getting values
y1 := x["bar"]     // zero value returned if no map entry exists for the key
y2, ok := x["bar"] // ok is a boolean, true if key exists in the map

// removing keys
delete(x, "foo")

// make a map with a literal
x = map[string]int{
	"foo": 2, "bar": 42, "baz": -1,
}


// empty map
var emptyMap = new HashMap<String, Integer>()

// map initialization
var map = {"Scott"->50, "Carson"->40, "Luca"->30, "Kyle"->38}

// map key/value assignment
map["Scott"] = 51

// get a value
var x = map["Scott"]

// remove an entry
map.remove("Scott")

// loop and maps
for(entry in map.entrySet()) {
  print("Key: ${entry.Key}, Value: ${entry.Value}")
}

// functional iteration
map.eachKey(\ k ->print(map[k]))
map.eachValue(\ v ->print(v))
map.eachKeyAndValue(\ k, v -> print("Key: ${v}, Value: ${v}"))
var filtered = map.filterByValues(\ v ->v < 50)

// any object can be treated as an associative array
class Person {
  var name: String
  var age: int
}
// access properties on Person dynamically via associative array syntax
var scott = new Person()
scott["name"] = "Scott"
scott["age"] = 29


map = [:]
map[7] = 7
map['foo'] = 'foovalue'
map.put('bar', 'barvalue')
map.moo = 'moovalue'

assert 7 == map[7]
assert 'foovalue' == map.foo
assert 'barvalue' == map['bar']
assert 'moovalue' == map.get('moo')


import Data.Map

dict = fromList [("key1","val1"), ("key2","val2")]

ans = Data.Map.lookup "key2" dict  -- evaluates to Just "val2"


let d         dict 2  # Initial estimated size
let d["test"] "test"  # Strings can be used as index
let d[123]    123     # Integers can also be used as index

println d["test"]
println d[123]


procedure main()
   local t
   t := table()
   t["foo"] := "bar"
   write(t["foo"])
end


Hash Bar is a room.

Connection relates various texts to one number. The verb to be connected to implies the connection relation.

"foo" is connected to 12.
"bar" is connected to 34.
"baz" is connected to 56.

When play begins:
	[change values]
	now "bleck" is connected to 78;
	[check values]
	if "foo" is connected to 12, say "good.";
	if "bar" is not connected to 56, say "good.";
	[retrieve values]
	let V be the number that "baz" relates to by the connection relation;
	say "'baz' => [V].";
	end the story.


coclass 'assocArray'
    encode=: 'z', (a.{~;48 65 97(+ i.)&.>10 26 26) {~ 62x #.inv 256x #. a.&i.
    get=: "[email protected]
    has=: 0 <: [email protected]<@encode
    set=:4 :'(encode x)=:y'


Map<String, Integer> map = new HashMap<String, Integer>();
map.put("foo", 5);
map.put("bar", 10);
map.put("baz", 15);
map.put("foo", 6);


var assoc = {};

assoc['foo'] = 'bar';
assoc['another-key'] = 3;

// dot notation can be used if the property name is a valid identifier
assoc.thirdKey = 'we can also do this!';
assoc[2] = "the index here is the string '2'";

//using JavaScript's object literal notation
var assoc = {
  foo: 'bar',
  'another-key': 3 //the key can either be enclosed by quotes or not
};

//iterating keys
for (var key in assoc) {
  // hasOwnProperty() method ensures the property isn't inherited
  if (assoc.hasOwnProperty(key)) {
    alert('key:"' + key + '", value:"' + assoc[key] + '"');
  }
}


# An empty object:
{}

# Its type:
{} | type
# "object"

# An object literal:
{"a": 97, "b" : 98}

# Programmatic object construction:
reduce ("a", "b", "c", "d") as $c ({}; . +  { ($c) : ($c|explode[.0])} )
# {"a":97,"c":99,"b":98,"d":100}

# Same as above:
reduce range (97;101) as $i ({}; . + { ([$i]|implode) : $i })

# Addition of a key/value pair by assignment:
{}["A"] = 65  # in this case, the object being added to is {}

# Alteration of the value of an existing key:
{"A": 65}["A"] = "AA"


var assoc = {};

assoc['foo'] = 'bar';
assoc['another-key'] = 3;

// dot notation can be used if the property name is a valid identifier
assoc.thirdKey = 'we can also do this!';
assoc[2] = "the index here is the string '2'";
;assoc;

//using JavaScript's object literal notation
var assoc = {
  foo: 'bar',
  'another-key': 3 //the key can either be enclosed by quotes or not
};

//iterating keys
for (var key in assoc) {
  // hasOwnProperty() method ensures the property isn't inherited
  if (assoc.hasOwnProperty(key)) {
    puts('key:"' + key + '", value:"' + assoc[key] + '"');
  }
}
;assoc;

/*
=!EXPECTSTART!=
associativeArray.jsi:12: warn: duplicate var: assoc
assoc ==> { 2:"the index here is the string \'2\'", "another-key":3, foo:"bar", thirdKey:"we can also do this!" }
key:"another-key", value:"3"
key:"foo", value:"bar"
assoc ==> { "another-key":3, foo:"bar" }
=!EXPECTEND!=
*/


dict = Dict('a' => 97, 'b' => 98) # list keys/values
# Dict{Char,Int64} with 2 entries:
#   'b' => 98
#   'a' => 97

dict = Dict(c => Int(c) for c = 'a':'d') # dict comprehension
# Dict{Char,Int64} with 4 entries:
#   'b' => 98
#   'a' => 97
#   'd' => 100
#   'c' => 99

dict['é'] = 233; dict # add an element
# Dict{Char,Int64} with 3 entries:
#   'b' => 98
#   'a' => 97
#   'é' => 233

emptydict = Dict() # create an empty dict
# Dict{Any,Any} with 0 entries

dict["a"] = 1 # type mismatch
# ERROR: MethodError: Cannot `convert` an object of type String to an object of type Char

typeof(dict) # type is infered correctly
# Dict{Char,Int64}


   / creating an dictionary
   d1:.((`foo;1); (`bar;2); (`baz;3))

   / extracting a value
   d1[`bar]
2


fun main(args: Array<String>) {
    // map definition:
    val map = mapOf("foo" to 5,
                    "bar" to 10,
                    "baz" to 15,
                    "foo" to 6)

    // retrieval:
    println(map["foo"]) // => 6
    println(map["invalid"]) // => null

    // check keys:
    println("foo" in map) // => true
    println("invalid" in map) // => false

    // iterate over keys:
    for (k in map.keys) print("$k ")
    println()

    // iterate over values:
    for (v in map.values) print("$v ")
    println()

    // iterate over key, value pairs:
    for ((k, v) in map) println("$k => $v")
}


1) a (currently) reduced set of functions:

HASH: [5] [H.lib, H.new, H.disp, H.get, H.set!]

2) building an associative array: {def H key value | ...}

{def capitals
 {H.new nyk New York, United States |
        lon London, United Kingdom |
        par Paris, France |
        mos Moscou, Russia }}
-> capitals

3) displaying: {H.disp hash}
{H.disp {capitals}}
->
[
nyk: New York, United States
lon: London, United Kingdom
par: Paris, France
mos: Moscou, Russia
]

4) getting a value from a key: {H.get hash key}

{H.get {capitals} nyk} -> New York, United States
{H.get {capitals} lon} -> London, United Kingdom
{H.get {capitals} par} -> Paris, France
{H.get {capitals} mos} -> Moscou, Russia

5) adding a new (key,value): {H.set! hash key value}

{H.disp {H.set! {capitals} bar Barcelona, Catalunya}}
->
[
nyk: New York, United States
lon: London, United Kingdom
par: Paris, France
mos: Moscou, Russia
bar: Barcelona, Catalunya
]

6) editing a key

{H.disp
  {H.set! {capitals}
          nyk
          {H.get {capitals} nyk} of America}} // adding "of America" to nyk
->
[
nyk: New York, United States of America
lon: London, United Kingdom
par: Paris, France
mos: Moscou, Russia
bar: Barcelona, Catalunya
]


: dip  swap '_ set execute _ ; : nip  swap drop ;
: first  0 extract nip ; : second  1 extract nip ;

: assoc-in  swap keys eq ;
: assoc-index'  over keys swap eq [1] index collapse ;
: at  swap assoc-index' subscript collapse second ;
: delete-at  swap assoc-index' first remove ;
: keys  1 transpose first ;
: set-at
    over 'dup dip assoc-in '+ reduce if 'dup dip delete-at then
    "swap 2 compress 1 compress" dip swap append ;

[['foo 5]]
10 'bar rot set-at
'bar over at .
'hello 'bar rot set-at
20 'baz rot set-at .


var .hash = h{1: "abc", "1": 789}

# may assign with existing or non-existing hash key (if hash is mutable)
.hash[7] = 49

writeln .hash[1]
writeln .hash[7]
writeln .hash["1"]

# using an alternate value in case of invalid index; prevents exception
writeln .hash[1; 42]
writeln .hash[2; 42]


// In Lasso associative arrays are called maps

// Define an empty map
local(mymap = map)

// Define a map with content
local(mymap = map(
	'one'	= 'Monday',
	'2'	= 'Tuesday',
	3	= 'Wednesday'
))

// add elements to an existing map
#mymap -> insert('fourth' = 'Thursday')

// retrieve a value from a map
#mymap -> find('2') // Tuesday
'
'
#mymap -> find(3) // Wednesday, found by the key not the position
'
'

// Get all keys from a map
#mymap -> keys // staticarray(2, fourth, one, 3)
'
'

// Iterate thru a map and get values
with v in #mymap do {^
	#v
	'
'
^}
// Tuesday
Thursday
Monday
Wednesday

// Perform actions on each value of a map
#mymap -> foreach => {
	#1 -> uppercase
	#1 -> reverse
}
#mymap // map(2 = YADSEUT, fourth = YADSRUHT, one = YADNOM, 3 = YADSENDEW)


(let* ((my-dict (: dict new))
       (my-dict (: dict store 'key-1 '"value 1" my-dict))
       (my-dict (: dict store 'key-2 '"value 2" my-dict)))
  (: io format '"size: ~p~n" (list (: dict size my-dict)))
  (: io format '"some data: ~p~n" (list (: dict fetch 'key-1 my-dict))))


data "red",      "255 50 50",       "green", "50 255 50",     "blue", "50 50 255"
data "my fave",  "220 120 120",     "black", "0 0 0"

myAssocList$ =""

for i =1 to 5
    read k$
    read dat$
    call sl.Set myAssocList$, k$, dat$
next i

print " Key 'green' is associated with data item "; sl.Get$( myAssocList$, "green")


props = [#key1: "value1", #key2: "value2"]

put props[#key2]
-- "value2"
put props["key2"]
-- "value2"
put props.key2
-- "value2"
put props.getProp(#key2)
-- "value2"


command assocArray
    local tArray
    put "value 1" into tArray["key 1"]
    put 123 into tArray["key numbers"]
    put "a,b,c" into tArray["abc"]

    put "number of elements:" && the number of elements of tArray & return & \
          "length of item 3:" && the length of tArray["abc"] & return & \
          "keys:" && the keys of tArray
end assocArray


pprop "animals "cat 5
pprop "animals "dog 4
pprop "animals "mouse 11
print gprop "animals "cat    ; 5
remprop "animals "dog
show plist "animals    ;  [mouse 11 cat 5]


HAI 1.2
I HAS A Hash ITZ A BUKKIT
Hash HAS A key1 ITZ "val1" BTW This works for identifier-like keys, like obj.key in JavaScript
Hash HAS A SRS "key-2" ITZ 1 BTW Non-identifier keys need the SRS
VISIBLE Hash'Z SRS "key-2"
KTHXBYE


Inventory A="100":=1, "200":=5, 10:=500,  20:="Hello There"
Print len(A)
Print A(100)=1, A(200)=5, A$(20)="Hello There"
Return A, 100:=3, 200:=7
\\ print all elements
Print A
For i=0 to Len(A)-1 {
      \\ Key, Value by current order (using !)
      Print Eval$(A, i), A$(i!)
}
\\ Iterator
Append A, "End":=5000
N=Each(A)
While N {
      Print Eval$(A, N^), A$(N^!)
}
Print Len(A)=5
Delete A, "100", 10, 20
Print Len(A)=2
If Exist(A, "End") Then Print Eval(A)=5000


/* No need to declare anything, undeclared arrays are hashed */

h[1]: 6;
h[9]: 2;

arrayinfo(h);
[hashed, 1, [1], [9]]


map = { 3: "test", "foo": 42 }

print map[3]
map[3] = "more tests"
print map[3]
print map["foo"]
print map.foo  // same as map["foo"] (only for string keys that are valid identifiers)


using System;
using System.Console;
using Nemerle.Collections;

module AssocArray
{
    Main() : void
    {
        def hash1 = Hashtable([(1, "one"), (2, "two"), (3, "three")]);
        def hash2 = Hashtable(3);
        foreach (e in hash1)
            hash2[e.Value] = e.Key;
        WriteLine("Enter 1, 2, or 3:");
        def entry = int.Parse(ReadLine());
        WriteLine(hash1[entry]);
    }
}


/* NetRexx */

options replace format comments java crossref symbols

key0 = '0'
key1 = 'key0'

hash = '.'            -- Initialize the associative array 'hash' to '.'
hash[key1] = 'value0' -- Set a specific key/value pair

say '<hash key="'key0'" value="'hash[key0]'" />' -- Display a value for a key that wasn't set
say '<hash key="'key1'" value="'hash[key1]'" />' -- Display a value for a key that was set


import tables

var
  hash = initTable[string, int]() # empty hash table
  hash1: Table[string, int]       # empty hash table (implicit initialization).
  hash2 = {"key1": 1, "key2": 2}.toTable # hash table with two keys
  hash3 = [("key1", 1), ("key2", 2)].toTable # hash table from tuple array
  hash4 = @[("key1", 1), ("key2", 2)].toTable # hash table from tuple seq
  value = hash2["key1"]

hash["spam"] = 1
hash["eggs"] = 2
hash["foo"] = 3

echo "hash has ", hash.len, " elements"
echo "hash has key foo? ", hash.hasKey("foo")
echo "hash has key bar? ", hash.hasKey("bar")

echo "iterate pairs:" # iterating over (key, value) pairs
for key, value in hash:
  echo key, ": ", value

echo "iterate keys:" # iterating over keys
for key in hash.keys:
  echo key

echo "iterate values:" # iterating over values
for key in hash.values:
  echo key


MODULE AssociativeArray;
IMPORT
  ADT:Dictionary,
  Object:Boxed,
  Out;
TYPE
  Key = STRING;
  Value = Boxed.LongInt;

VAR
  assocArray: Dictionary.Dictionary(Key,Value);
  iterK: Dictionary.IterKeys(Key,Value);
  iterV: Dictionary.IterValues(Key,Value);
  aux: Value;
  k: Key;

BEGIN
  assocArray := NEW(Dictionary.Dictionary(Key,Value));
  assocArray.Set("ten",NEW(Value,10));
  assocArray.Set("eleven",NEW(Value,11));

  aux := assocArray.Get("ten");
  Out.LongInt(aux.value,0);Out.Ln;
  aux := assocArray.Get("eleven");
  Out.LongInt(aux.value,0);Out.Ln;Out.Ln;

  (* Iterate keys *)
  iterK := assocArray.IterKeys();
  WHILE (iterK.Next(k)) DO
    Out.Object(k);Out.Ln
  END;

  Out.Ln;

  (* Iterate values *)
  iterV := assocArray.IterValues();
  WHILE (iterV.Next(aux)) DO
    Out.LongInt(aux.value,0);Out.Ln
  END

END AssociativeArray.


# create map
map := StringMap->New();
# insert
map->Insert("two", IntHolder->New(2)->As(Base));
map->Insert("thirteen", IntHolder->New(13)->As(Base));
map->Insert("five", IntHolder->New(5)->As(Base));
map->Insert("seven", IntHolder->New(7)->As(Base));
# find
map->Find("thirteen")->As(IntHolder)->GetValue()->PrintLine();
map->Find("seven")->As(IntHolder)->GetValue()->PrintLine();


NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    @"Joe Doe", @"name",
    [NSNumber numberWithUnsignedInt:42], @"age",
    [NSNull null], @"extra",
    nil];


let hash = Hashtbl.create 0;;
List.iter (fun (key, value) -> Hashtbl.add hash key value)
  ["foo", 5; "bar", 10; "baz", 15];;


;;; empty associative array
#empty
; or short form
#e

;;; creating the new empty associative array
(define empty-map #empty)

;;; creating associative array with values
(define my-map (pairs->ff '(
   (1 . 100)
   (2 . 200)
   (7 . 777))))
;;; or in short form (available from Ol version 2.1)
(define my-map {
   1 100
   2 200
   7 777})

;;; add new key-value pair to the existing associative array
(define my-new-map (put my-map 'the-key 'the-value))

;;; print our arrays
(print empty-map)
; ==> #()

(print my-map)
; ==> #((1 . 100) (2 . 200) (7 . 777))

(print my-new-map)
; ==> #((1 . 100) (2 . 200) (7 . 777) (the-key . the-value))


map = .directory~new
map["foo"] = 5
map["bar"] = 10
map["baz"] = 15
map["foo"] = 6


def n 200

Class AssociativeArray
'=====================

  indexbase 1
  string s[n]
  sys    max

  method find(string k) as sys
  sys i,e
  e=max*2
  for i=1 to e step 2
    if k=s[i] then return i
  next
  end method

  method dat(string k) as string
  sys i=find(k)
  if i then return s[i+1]
  end method

  method dat(string k, d) as sys
  sys i=find(k)
  if i=0 then
    if max>=n
      print "Array overflow" : return 0
    end if
    max+=1
    i=max*2-1
    s[i]=k
  end if
  s[i+1]=d
  return i
  end method

end class

'====
'TEST
'====

AssociativeArray A

'fill
A.s<={"shoes","LC1",  "ships","LC2",  "sealingwax","LC3",  "cabbages","LC4",  "kings","LC5"}
A.max=5
'access
print A.dat("ships")       'result LC2
A.dat("computers")="LC99"  '
print A.dat("computers")   'result LC99


declare
  Dict = {Dictionary.new}
in
  Dict.foo := 5
  Dict.bar := 10
  Dict.baz := 15
  Dict.foo := 20

  {Inspect Dict}


# using => key does not need to be quoted unless it contains special chars
my %hash = (
  key1 => 'val1',
  'key-2' => 2,
  three => -238.83,
  4 => 'val3',
);

# using , both key and value need to be quoted if containing something non-numeric in nature
my %hash = (
  'key1', 'val1',
  'key-2', 2,
  'three', -238.83,
  4, 'val3',
);


with javascript_semantics
setd("one",1)
setd(2,"duo")
setd({3,4},{5,"six"})
?getd("one")                                    -- shows 1
?getd({3,4})                                    -- shows {5,"six"}
?getd(2)                                        -- shows "duo"
deld(2)
?getd(2)                                        -- shows 0


include ..\Utilitys.pmt

def getd    /# dict key -- dict data #/
    swap 1 get rot find nip
    dup if
        swap 2 get rot get nip
    else
        drop "Unfound"
    endif
enddef

def setd    /# dict ( key data ) -- dict #/
    1 get var ikey
    2 get var idata
    drop
    1 get ikey find var p drop
    p if
        2 get idata p set 2 set
    else
        2 get idata 0 put 2 set
        1 get ikey 0 put 1 set
    endif
enddef

( ( ) ( ) )

( 1 "one" ) setd
( "two" 2 ) setd
( PI PI ) setd

1 getd print nl
"two" getd print nl
PI getd tostr print nl
3 getd print


$array = array();
$array = []; // Simpler form of array initialization
$array['foo'] = 'bar';
$array['bar'] = 'foo';

echo($array['foo']); // bar
echo($array['moo']); // Undefined index

// Alternative (inline) way
$array2 = array('fruit' => 'apple',
                'price' => 12.96,
                'colour' => 'green');

// Another alternative (simpler) way
$array2 = ['fruit' => 'apple',
                'price' => 12.96,
                'colour' => 'green'];

// Check if key exists in the associative array
echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null


go =>

   % Create an empty map
   Map = new_map(),
   println(Map),

   % add some data
   Map.put(a,1),
   Map.put("picat",2),
   Map.put("picat",3), % overwrite values
   % Add a new value (a long list of different stuff)
   Map.put([a,list,of,different,"things",[including, lists],3.14159],2),
   println(Map),

   println(a=Map.get(a)), % get a value
   println(b=Map.get(b,'default value')), % the second argument to get/2 is the default value

   % create a map from a list of values
   Map2 = new_map([K=V : {K,V} in zip([a,b,c,d,e,f,g,h],1..8)]),
   println(Map2),
   println(h=Map2.get(h)),

   % Check if there is a value in the map
   if not Map2.has_key(z) then
     println("no key 'z'")
   end,

   % keys() and value() returns unsorted list of elements
   % so we sort them.
   println(keys=Map2.keys().sort()),
   println(values=Map2.values().sort()),

   % Print the values for the keys that are even
   println([K : K=V in Map2, V mod 2=0].sort),

   nl.


(put 'A 'foo 5)
(put 'A 'bar 10)
(put 'A 'baz 15)
(put 'A 'foo 20)

: (get 'A 'bar)
-> 10

: (get 'A 'foo)
-> 20

: (show 'A)
A NIL
   foo 20
   bar 10
   baz 15


mapping m = ([ "apple": "fruit", 17: "seventeen" ]);
write("indices: %O\nvalues: %O\n17: %O\n",
      indices(m),
      values(m),
      m[17]);


*process source xref attributes or(!);
 assocarr: Proc Options(main);
 Dcl 1 aa,
      2 an Bin Fixed(31) Init(0),
      2 pairs(100),
       3 key Char(10) Var,
       3 val Char(10) Var;
 Dcl hi Char(10) Value((high(10)));
 Dcl i  Bin Fixed(31);
 Dcl k Char(10) Var;

 Call aadd('1','spam');
 Call aadd('2','eggs');
 Call aadd('3','foo');
 Call aadd('2','spam');
 Call aadd('4','spam');

 Put Skip(' ');
 Put Edit('Iterate over keys')(Skip,a);
 Do i=1 To an;
   k=key(i);
   Put Edit('>'!!k!!'< => >'!!aacc(k)!!'<')(Skip,a);
   End;

 aadd: Proc(k,v);
 Dcl (k,v) Char(*) Var;
 If aacc(k)^=hi Then
   Put Edit('Key >',k,'< would be a duplicate, not added.')
           (Skip,a,a,a);
 Else Do;
   an+=1;
   key(an)=k;
   val(an)=v;
   Put Edit('added >'!!k!!'< -> '!!v!!'<')(Skip,a);
   End;
 End;

 aacc: Proc(k) Returns(Char(10) Var);
 Dcl k Char(*) Var;
 Dcl v Char(10) Var;
 Dcl i Bin Fixed(31);
 Do i=1 To an;
   If key(i)=k Then
     Return(val(i));
   End;
 Return(hi);
 End;

 End;


DECLARE
    type ThisIsNotAnAssocArrayType is record (
        myShape VARCHAR2(20),
        mySize number,
        isActive BOOLEAN
    );
    assocArray ThisIsNotAnAssocArrayType ;
BEGIN
    assocArray.myShape := 'circle';

    dbms_output.put_line ('assocArray.myShape: ' || assocArray.myShape);
    dbms_output.put_line ('assocArray.mySize: ' || assocArray.mySize);
END;
/


;;; Create expandable hash table of initial size 50 and with default
;;; value 0 (default value is returned when the item is absent).
vars ht = newmapping([], 50, 0, true);
;;; Set value corresponding to string 'foo'
12 -> ht('foo');
;;; print it
ht('foo') =>
;;; Set value corresponding to vector {1 2 3}
17 -> ht({1 2 3});
;;; print it
ht({1 2 3}) =>
;;; Set value corresponding to number 42 to vector {0 1}
{0 1} -> ht(42);
;;; print it
ht(42) =>

;;; Iterate over keys printing keys and values.
 appproperty(ht,
    procedure (key, value);
      printf(value, '%p\t');
      printf(key, '%p\n');
     endprocedure);


mydictionary = (red=0xff0000, green=0x00ff00, blue=0x0000ff)

redblue = "purple"
mydictionary put(redblue, 0xff00ff)

255 == mydictionary("blue")
65280 == mydictionary("green")
16711935 == mydictionary("purple")


mymap(key1,value1).
mymap(key2,value2).

?- mymap(key1,V).
   V = value1


NewMap dict.s()
dict("country") = "Germany"
Debug dict("country")


hash = dict()  # 'dict' is the dictionary type.
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = { 'key1':1, 'key2':2, }
value = hash[key]


#lang racket

;; a-lists
(define a-list '((a . 5) (b . 10)))
(assoc a-list 'a) ; => '(a . 5)

;; hash tables
(define table #hash((a . 5) (b . 10)))
(hash-ref table 'a) ; => 5

;; dictionary interface
(dict-ref a-list 'a) ; => 5
(dict-ref table 'a)  ; => 5


my %h1 = key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3';
my %h2 = 'key1', 'val1', 'key-2', 2, 'three', -238.83, 4, 'val3';

# Creating a hash from two lists using a metaoperator.

my @a = 1..5;
my @b = 'a'..'e';
my %h = @a Z=> @b;

# Hash elements and hash slices now use the same sigil as the whole hash. This is construed as a feature.
# Curly braces no longer auto-quote, but Raku's qw (shortcut < ... >) now auto-subscripts.

say %h1{'key1'};
say %h1<key1>;
%h1<key1> = 'val1';
%h1<key1 three> = 'val1', -238.83;

# Special syntax is no longer necessary to access a hash stored in a scalar.

my $h = {key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3'};
say $h<key1>;

# Keys are of type Str or Int by default. The type of the key can be provided.

my %hash{Any}; # same as %hash{*}
class C {};
my %cash{C};
%cash{C.new} = 1;


{ 'a' 1 'b' 2 'c' 3.14 'd' 'xyz' } as a_hash
a_hash print

hash (4 items)
 a => 1
 b => 2
 c => 3.14
 d => "xyz"

a_hash 'c' get         # get key 'c'
6.28 a_hash 'c' set    # set key 'c'
a_hash.'c'             # get key 'c' shorthand
6.28 a_hash:'c'        # set key 'c' shorthand


relation key, value
insert "foo", "bar"
insert "bar", "foo"
insert "fruit", "apple"
assert unique key
print
select key == "fruit"
print


with hashTable'
hashTable constant table

table %{ first = 100 }%
table %{ second = "hello, world!" keepString %}

table @" first" putn
table @" second" puts


/* Rexx */

key0 = '0'
key1 = 'key0'

stem. = '.'                    /* Initialize the associative array 'stem' to '.' */
stem.key1 = 'value0'           /* Set a specific key/value pair                  */

Say 'stem.key0= 'stem.key  /* Display a value for a key that wasn't set */
Say 'stem.key1= 'stem.key1 /* Display a value for a key that was set    */


# Project  Associative array/Creation

myarray = [["one",1],
                 ["two",2],
                 ["three",3]]
see find(myarray,"two",1) + nl
see find(myarray,2,2) + nl


x = <<>>;  // create an empty list using strings as identifiers.
x.red   = strtod("0xff0000");  // RLaB doesn't deal with hexadecimal numbers directly. Thus we
x.green = strtod("0x00ff00");  // convert it to real numbers using ''strtod'' function.
x.blue  = strtod("0x0000ff");

// print content of a list
for (i in members(x))
{ printf("%8s %06x\n", i, int(x.[i])); }  // we have to use ''int'' function to convert reals to integers so "%x" format works

// deleting a key/value
clear (x.red);

// we can also use numeric identifiers in the above example
xid = members(x);  // this is a string array

for (i in 1:length(xid))
{ printf("%8s %06x\n", xid[i], int(x.[ xid[i] ])); }

// Finally, we can use numerical identifiers
// Note: ''members'' function orders the list identifiers lexicographically, in other words
// instead of, say, 1,2,3,4,5,6,7,8,9,10,11 ''members'' returns 1,10,11,2,3,4,5,6,7,8,9
x = <<>>;  // create an empty list
for (i in 1:5)
{ x.[i] = i; }  // assign to the element of list ''i'' the real value equal to i.


hash={}
hash[666]='devil'
hash[777]  # => nil
hash[666]  # => 'devil'


use std::collections::HashMap;
fn main() {
    let mut olympic_medals = HashMap::new();
    olympic_medals.insert("United States", (1072, 859, 749));
    olympic_medals.insert("Soviet Union", (473, 376, 355));
    olympic_medals.insert("Great Britain", (246, 276, 284));
    olympic_medals.insert("Germany", (252, 260, 270));
    println!("{:?}", olympic_medals);
}


class MAIN is
  main is
    -- creation of a map between strings and integers
    map ::= #MAP{STR, INT};

    -- add some values
    map := map.insert("red", 0xff0000);
    map := map.insert("green", 0xff00);
    map := map.insert("blue", 0xff);

    #OUT + map + "\n"; -- show the map...

    -- test if "indexes" exist
    #OUT +  map.has_ind("red") + "\n";
    #OUT +  map.has_ind("carpet") + "\n";

    -- retrieve a value by index
    #OUT + map["green"] + "\n";
  end;
end;


// immutable maps
var map = Map(1 -> 2, 3 -> 4, 5 -> 6)
map(3) // 4
map = map + (44 -> 99) // maps are immutable, so we have to assign the result of adding elements
map.isDefinedAt(33) // false
map.isDefinedAt(44) // true


(define my-dict '((a b) (1 hello) ("c" (a b c)))
(assoc 'a my-dict)                               ; evaluates to '(a b)


$ include "seed7_05.s7i";

# Define hash type
const type: myHashType is hash [string] integer;

# Define hash table
var myHashType: aHash is myHashType.value;

const proc: main is func
  local
    var string: stri is "";
    var integer: number is 0;
  begin
    # Add elements
    aHash @:= ["foo"] 42;
    aHash @:= ["bar"] 100;

    # Check presence of an element
    if "foo" in aHash then

      # Access an element
      writeln(aHash["foo"]);
    end if;

    # Change an element
    aHash @:= ["foo"] 7;

    # Remove an element
    excl(aHash, "foo");

    # Loop over the hash values
    for number range aHash do
      writeln(number);
    end for;

    # Loop over the hash keys
    for key stri range aHash do
      writeln(stri);
    end for;

    # Loop over hash keys and values
    for number key stri range aHash do
      writeln("key: " <& stri <& ", value: " <& number);
    end for;
  end func;


put {} into emptyPlist
put an empty property list into emptyPlist2

put {first:"Albert", last:"Einstein"} into Einstein
set Einstein's occupation to "Physicist"
put 1879 into Einstein.yearBorn
put "!!!" after the occupation of Einstein
put Einstein


* Iterate over key-value pairs of a map

    map = new('map 1:one 2:two 3:three')

visit(domain(map),'expr to evaluate for each member')

visit(range(map),'expr to evaluate for each member')

    next
        this = next(map)             :f(done)
        out(show(this) ':' show(get(map,this)) :next)
    done

    loop(d = domain(map)

    next
        out('next domain entry',next(d))    :s(next)
    done

    loop(d = range(map)

    next
        out('next domain entry',next(d))    :s(next)
    done


var hash = Hash.new(
    key1 => 'value1',
    key2 => 'value2',
);

# Add a new key-value pair
hash{:key3} = 'value3';


Dictionary new*, 'MI' -> 'Michigan', 'MN' -> 'Minnesota'


states := Dictionary new.
states at: 'MI' put: 'Michigan'.
states at: 'MN' put: 'Minnesota'.


	t = table()
	t<"red"> = "#ff0000"
	t<"green"> = "#00ff00"
	t<"blue"> = "#0000ff"

	output = t<"red">
	output = t<"blue">
	output = t<"green">
end


REM CREATE a TABLE TO associate KEYS WITH VALUES
CREATE TABLE  associative_array ( KEY_COLUMN VARCHAR2(10), VALUE_COLUMN VARCHAR2(100)); .
REM INSERT a KEY VALUE Pair
INSERT (KEY_COLUMN, VALUE_COLUMN) VALUES ( 'VALUE','KEY');.
REM Retrieve a KEY VALUE pair
SELECT aa.value_column FROM associative_array aa WHERE aa.key_column = 'KEY';


--#SET TERMINATOR @

SET SERVEROUTPUT ON @

BEGIN
 DECLARE TYPE ASSOC_ARRAY AS VARCHAR(20) ARRAY [VARCHAR(20)];
 DECLARE HASH ASSOC_ARRAY;
 SET HASH['key1'] = 'val1';
 SET HASH['key-2'] = 2;
 SET HASH['three'] = -238.83;
 SET HASH[4] = 'val3';

 CALL DBMS_OUTPUT.PUT_LINE(HASH['key1']);
 CALL DBMS_OUTPUT.PUT_LINE(HASH['key-2']);
 CALL DBMS_OUTPUT.PUT_LINE(HASH['three']);
 CALL DBMS_OUTPUT.PUT_LINE(HASH[4]);
 CALL DBMS_OUTPUT.PUT_LINE(HASH['5']);
END@


mata
a=asarray_create()

// Add entries
asarray(a,"one",1)
asarray(a,"two",2)

// Check existence of key
asarray_contains(a,"two")

// Get a vector of all keys
asarray_keys(a)

// Number of entries
asarray_elements(a)

// End Mata session
end


// make an empty map
var a = [String: Int]()
// or
var b: [String: Int] = [:]

// make an empty map with an initial capacity
var c = [String: Int](minimumCapacity: 42)

// set a value
c["foo"] = 3

// make a map with a literal
var d = ["foo": 2, "bar": 42, "baz": -1]


 #+ 'name=bob' $hash   | add to hash
 #? 'name' $hash $S    | find 'name' and return 'bob' in $S
 #- 'name' $hash       | delete 'name=bob' from hash


# Create one element at a time:
set hash(foo) 5

# Create in bulk:
array set hash {
    foo 5
    bar 10
    baz 15
}

# Access one element:
set value $hash(foo)

# Output all values:
foreach key [array names hash] {
    puts $hash($key)
}


needs asarray

( create an associative array )
1024 cells is-asarray foo

( store 100 as the "first" element in the array )
100 " first" foo asarray.put

( store 200 as the "second" element in the array )
200 " second" foo asarray.put

( obtain and print the values )
" first" foo asarray.get .
" second" foo asarray.get .


typeset -A hash
hash=( [key1]=val1 [key2]=val2 )
hash[key3]=val3
echo "${hash[key3]}"


map='p.map'

function init() {
cat <<EOF > $map
apple a
boy b
cat c
dog d
elephant e
EOF
}

function put() {
    k=$1; v=$2;
    del $k
    echo $v $k >> $map
 }

function get() {
    k=$1
    for v in $(cat $map | grep "$k$"); do
        echo $v
        break
    done
 }

function del() {
    k=$1
    temp=$(mktemp)
    mv $map $temp
    cat $temp | grep -v "$k$" > $map
}

function dump() {
    echo "-- Dump begin --"
    cat $map
    echo "-- Dump complete --"
}

init
get c
put c cow
get c
dump


using Gee;

void main(){
    var	map = new HashMap<string, int>(); // creates a HashMap with keys of type string, and values of type int

    // two methods to set key,value pair
    map["one"] = 1;
    map["two"] = 2;

    map.set("four", 4);
    map.set("five", 5);

    // two methods of getting key,value pair
    stdout.printf("%d\n", map["one"]);

    stdout.printf("%d\n", map.get("two"));
}


Option Explicit
Sub Test()
    Dim h As Object
    Set h = CreateObject("Scripting.Dictionary")
    h.Add "A", 1
    h.Add "B", 2
    h.Add "C", 3
    Debug.Print h.Item("A")
    h.Item("C") = 4
    h.Key("C") = "D"
    Debug.Print h.exists("C")
    h.Remove "B"
    Debug.Print h.Count
    h.RemoveAll
    Debug.Print h.Count
End Sub


" Creating a dictionary with some initial values
let dict = {"one": 1, "two": 2}

" Retrieving a value
let two_a = dict["two"]
let two_b = dict.two
let two_c = get(dict, "two", "default value for missing key")

" Modifying a value
let dict["one"] = 1.0
let dict.two = 2.0

" Adding a new value
let dict["three"] = 3
let dict.four = 4

" Removing a value
let one = remove(dict, "one")
unlet dict["two"]
unlet dict.three


LOCAL loCol As Collection, k, n, o
CLEAR
*!* Example using strings
loCol = NEWOBJECT("Collection")
loCol.Add("Apples", "A")
loCol.Add("Oranges", "O")
loCol.Add("Pears", "P")
n = loCol.Count
? "Items:", n
*!* Loop through the collection
k = 1
FOR EACH o IN loCol FOXOBJECT
    ? o, loCol.GetKey(k)
    k = k + 1
ENDFOR
*!* Get an item by its key
? loCol("O")
?
*!* Example using objects
LOCAL loFruits As Collection
loFruits = NEWOBJECT("Collection")
loFruits.Add(CREATEOBJECT("fruit", "Apples"), "A")
loFruits.Add(CREATEOBJECT("fruit", "Oranges"), "O")
loFruits.Add(CREATEOBJECT("fruit", "Pears"), "P")
*!* Loop through the collection
k = 1
FOR EACH o IN loFruits FOXOBJECT
    ? o.Name, loFruits.GetKey(k)
    k = k + 1
ENDFOR
*!* Get an item name by its key
? loFruits("P").Name

DEFINE CLASS fruit As Custom
PROCEDURE Init(tcName As String)
THIS.Name = tcName
ENDPROC
ENDDEFINE


fn main() {
    // make empty map
    mut my_map := map[string]int{}

    //s et value
    my_map['foo'] = 3

    // getting values
    y1 := my_map['foo']

    // remove keys
    my_map.delete('foo')

    // make map with values
    my_map = {
        'foo': 2
        'bar': 42
        'baz': -1
    }
}


var fruit = {}                   // creates an empty map
fruit[1] = "orange"              // associates a key of 1 with "orange"
fruit[2] = "apple"               // associates a key of 2 with "apple"
System.print(fruit[1])           // retrieves the value with a key of 1 and prints it out
fruit.remove(1)                  // removes the entry with a key of 1 from the map
System.print(fruit)              // prints the rest of the map
System.print()
var capitals = {                 // creates a new map with three entries
    "France": "Paris",
    "Germany": "Berlin",
    "Spain": "Madrid"
}
capitals["Russia"] = "Moscow"    // adds another entry
System.print(capitals["France"]) // retrieves the "France" entry and prints out its capital
capitals.remove("France")        // removes the "France" entry
System.print(capitals)           // prints all remaining entries
System.print(capitals.count)     // prints the number of remaining entries
System.print(capitals["Sweden"]) // prints the entry for Sweden (null as there isn't one)


include c:\cxpl\stdlib;
char Dict(10,10);
int  Entries;

proc AddEntry(Letter, Greek);   \Insert entry into associative array
char Letter, Greek;
[Dict(Entries,0):= Letter;
StrCopy(Greek, @Dict(Entries,1));
Entries:= Entries+1;            \(limit checks ignored for simplicity)
];

func Lookup(Greek);             \Given Greek name return English letter
char Greek;
int  I;
[for I:= 0, Entries-1 do
    if StrCmp(Greek, @Dict(I,1)) = 0 then return Dict(I,0);
return ^?;
];

[Entries:= 0;
AddEntry(^A, "alpha");
AddEntry(^D, "delta");
AddEntry(^B, "beta");
AddEntry(^C, "gamma");
ChOut(0, Lookup("beta"));  CrLf(0);
ChOut(0, Lookup("omega")); CrLf(0);
]


zkl: Dictionary("one",1, "two",2, "three",3)
D(two:2,three:3,one:1)

zkl: T("one",1, "two",2, "three",3).toDictionary()
D(two:2,three:3,one:1)


ArrayRam equ $00FF2000   ;this label points to 4k of free space.

;concatenate Array1 + Array2
LEA ArrayRam,A0
LEA Array1,A1
MOVE.W #5-1,D1  ;LEN(Array1), measured in words.
JSR memcpy_w
;after this, A0 will point to the destination of the second array.

LEA Array2,A1   ;even though the source arrays are stored back-to-back in memory, we'll assume they're not just for demonstration purposes.
MOVE.W #5-1,D1  ;LEN(Array2), measured in words
JSR memcpy_w

JMP *           ;halt the CPU
memcpy_w:
MOVE.W (A1)+,(A0)+
DBRA D1,memcpy_w
rts

Array1:
DC.W 1,2,3,4,5
Array2:
DC.W 6,7,8,9,10


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program concAreaString.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBMAXITEMS,  20   //
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessLenArea: .asciz "The length of area 3  is : @ \n"
szCarriageReturn:  .asciz "\n"

/* areas strings  */
szString1:  .asciz "Apples"
szString2:  .asciz "Oranges"
szString3:  .asciz "Pommes"
szString4:  .asciz "Raisins"
szString5:  .asciz "Abricots"

/* pointer items area 1*/
tablesPoi1:
pt1_1:           .quad szString1
pt1_2:           .quad szString2
ptVoid_1:        .quad 0

/* pointer items area 2*/
tablesPoi2:
pt2_1:           .quad szString3
pt2_2:           .quad szString4
pt2_3:           .quad szString5
ptVoid_2:        .quad 0
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
tablesPoi3:    .skip   8 * NBMAXITEMS
sZoneConv:     .skip 30
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                       // entry of program

                            // copy area 1 ->  area 3
    ldr x1,qAdrtablesPoi1   // begin pointer area 1
    ldr x3,qAdrtablesPoi3   // begin pointer area 3
    mov x0,0                // counter
1:
    ldr x2,[x1,x0,lsl 3]    // read string pointer address item x0 (8 bytes by pointer)
    cbz x2,2f               // is null ?
    str x2,[x3,x0,lsl 3]    // no store pointer in area 3
    add x0,x0,1             // increment counter
    b 1b                    // and loop
2:                          // copy area 2 ->  area 3
    ldr x1,qAdrtablesPoi2   // begin pointer area 2
    ldr x3,qAdrtablesPoi3   // begin pointer area 3
    mov x4,#0               // counter area 2
3:                          // x0 contains the first void item in area 3
    ldr x2,[x1,x4,lsl #3]   // read string pointer address item x0 (8 bytes by pointer)
    cbz x2,4f               // is null ?
    str x2,[x3,x0,lsl #3]   // no store pointer in area 3
    add x0,x0,1             // increment counter
    add x4,x4,1             // increment counter
    b 3b                    // and loop
4:
                            // count items number in area 3
    ldr x1,qAdrtablesPoi3   // begin pointer table
    mov x0,#0               // counter
5:                          // begin loop
    ldr x2,[x1,x0,lsl #3]   // read string pointer address item x0 (8 bytes by pointer)
    cmp x2,#0               // is null ?
    cinc x0,x0,ne           // no increment counter
    bne 5b                  // and loop

    ldr x1,qAdrsZoneConv    // conversion decimal
    bl conversion10S
    ldr x0,qAdrszMessLenArea
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc   // insert result at @ character
    bl affichageMess

100:                        // standard end of the program
    mov x0,0                // return code
    mov x8,EXIT             // request to exit program
    svc 0                   // perform the system call
qAdrtablesPoi1:        .quad tablesPoi1
qAdrtablesPoi2:        .quad tablesPoi2
qAdrtablesPoi3:        .quad tablesPoi3
qAdrszMessLenArea:     .quad szMessLenArea
qAdrsZoneConv:         .quad sZoneConv
qAdrszCarriageReturn:  .quad szCarriageReturn
/****************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


report z_array_concatenation.

data(itab1) = value int4_table( ( 1 ) ( 2 ) ( 3 ) ).
data(itab2) = value int4_table( ( 4 ) ( 5 ) ( 6 ) ).

append lines of itab2 to itab1.

loop at itab1 assigning field-symbol(<line>).
    write <line>.
endloop.


BYTE FUNC Concat(INT ARRAY src1,src2,dst BYTE size1,size2)
  BYTE i

  FOR i=0 TO size1-1
  DO
    dst(i)=src1(i)
  OD
  FOR i=0 TO size2-1
  DO
    dst(size1+i)=src2(i)
  OD
RETURN (size1+size2)

PROC PrintArray(INT ARRAY a BYTE size)
  BYTE i

  Put('[)
  FOR i=0 TO size-1
  DO
    PrintI(a(i))
    IF i<size-1 THEN
      Put(' )
    FI
  OD
  Put('])
RETURN

PROC Test(INT ARRAY src1,src2 BYTE size1,size2)
  INT ARRAY res(20)
  BYTE size

  size=Concat(src1,src2,res,size1,size2)
  PrintArray(src1,size1)
  Put('+)
  PrintArray(src2,size2)
  Put('=)
  PrintArray(res,size)
  PutE() PutE()
RETURN

PROC Main()
  INT ARRAY
    a1=[1 2 3 4],
    a2=[5 6 7 8 9 10],
    ;a workaround for a3=[-1 -2 -3 -4 -5]
    a3=[65535 65534 65533 65532 65531]

  Test(a1,a2,4,6)
  Test(a2,a1,6,4)
  Test(a3,a2,5,4)
RETURN


var array1:Array = new Array(1, 2, 3);
var array2:Array = new Array(4, 5, 6);
var array3:Array = array1.concat(array2); //[1, 2, 3, 4, 5, 6]


type T is array (Positive range <>) of Integer;
X : T := (1, 2, 3);
Y : T := X & (4, 5, 6); -- Concatenate X and (4, 5, 6)


ac(list a, b)
{
    list o;

    o.copy(a);
    b.ucall(l_append, 1, o);

    o;
}

main(void)
{
    list a, b, c;

    a = list(1, 2, 3, 4);
    b = list(5, 6, 7, 8);

    c = ac(a, b);

    c.ucall(o_, 1, " ");

    0;
}


MODE ARGTYPE = INT;
MODE ARGLIST = FLEX[0]ARGTYPE;

OP + = (ARGLIST a, b)ARGLIST: (
  [LWB a:UPB a - LWB a + 1 + UPB b - LWB b + 1 ]ARGTYPE out;
  (
    out[LWB a:UPB a]:=a,
    out[UPB a+1:]:=b
  );
  out
);

# Append #
OP +:=    = (REF ARGLIST lhs, ARGLIST rhs)ARGLIST: lhs := lhs + rhs;
OP PLUSAB = (REF ARGLIST lhs, ARGLIST rhs)ARGLIST: lhs := lhs + rhs;

# Prefix #
OP +=:    = (ARGLIST lhs, REF ARGLIST rhs)ARGLIST: rhs := lhs + rhs;
OP PLUSTO = (ARGLIST lhs, REF ARGLIST rhs)ARGLIST: rhs := lhs + rhs;

ARGLIST a := (1,2),
        b := (3,4,5);

print(("a + b",a + b, new line));

VOID(a +:= b);
print(("a +:= b", a, new line));

VOID(a +=: b);
print(("a +=: b", b, new line))


begin
    integer array a ( 1 :: 5 );
    integer array b ( 2 :: 4 );
    integer array c ( 1 :: 8 );

    % concatenates the arrays a and b into c                        %
    % the lower and upper bounds of each array must be specified in %
    % the corresponding *Lb and *Ub parameters                      %
    procedure arrayConcatenate ( integer array a ( * )
                               ; integer value aLb, aUb
                               ; integer array b ( * )
                               ; integer value bLb, bUb
                               ; integer array c ( * )
                               ; integer value cLb, cUb
                               ) ;
        begin
            integer cPos;
            assert( ( cUb - cLb ) + 1 >= ( ( aUb + bUb ) - ( aLb + bLb ) ) - 2 );
            cPos := cLb;
            for aPos := aLb until aUb do begin
                c( cPos ) := a( aPos );
                cPos := cPos + 1
            end for_aPos ;
            for bPos := bLb until bUb do begin
                c( cPos ) := b( bPos );
                cPos := cPos + 1
            end for_bPos
        end arrayConcatenate ;

    % test arrayConcatenate                                          %
    for aPos := 1 until 5 do a( aPos ) := aPos;
    for bPos := 2 until 4 do b( bPos ) := - bPos;
    arrayConcatenate( a, 1, 5, b, 2, 4, c, 1, 8 );
    for cPos := 1 until 8 do writeon( i_w := 1, s_w := 1, c( cPos ) )

end.


#include <hbasic.h>
Begin
  a1 = {}
  a2 = {}
  Take(100,"Hola",0.056,"Mundo!"), and Push All(a1)
  Take("Segundo",0,"array",~True,~False), and Push All(a2)
  Concat (a1, a2) and Print ( a2, Newl )
End


List<String> listA = new List<String> { 'apple' };
List<String> listB = new List<String> { 'banana' };
listA.addAll(listB);
System.debug(listA); // Prints (apple, banana)


set listA to {1, 2, 3}
set listB to {4, 5, 6}
return listA & listB


/* ARM assembly Raspberry PI  */
/*  program concAreaString.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
.equ NBMAXITEMS,  20   @
/* Initialized data */
.data
szMessLenArea: .ascii "The length of area 3  is : "
sZoneconv:		 .fill 12,1,' '
szCarriageReturn:  .asciz "\n"

/* areas strings  */
szString1:  .asciz "Apples"
szString2:  .asciz "Oranges"
szString3:  .asciz "Pommes"
szString4:  .asciz "Raisins"
szString5:  .asciz "Abricots"

/* pointer items area 1*/
tablesPoi1:
pt1_1:		.int szString1
pt1_2:   .int szString2
ptVoid_1:		.int 0

/* pointer items area 2*/
tablesPoi2:
pt2_1:		.int szString3
pt2_2:   	.int szString4
pt2_3:   	.int szString5
ptVoid_2:		.int 0

/* UnInitialized data */
.bss
tablesPoi3:    .skip   4 * NBMAXITEMS

/*  code section */
.text
.global main
main:                /* entry of program  */
    push {fp,lr}    /* saves 2 registers */

    @ copy area 1 ->  area 3
    ldr r1,iAdrtablesPoi1  @ begin pointer area 1
    ldr r3,iAdrtablesPoi3  @ begin pointer area 3
    mov r0,#0    @ counter
1:
    ldr r2,[r1,r0,lsl #2]    @ read string pointer address item r0 (4 bytes by pointer)
    cmp r2,#0                @ is null ?
    strne r2,[r3,r0,lsl #2]    @ no store pointer in area 3
    addne r0,#1             @ increment counter
    bne 1b                  @ and loop
    @ copy area 2 ->  area 3
    ldr r1,iAdrtablesPoi2  @ begin pointer area 2
    ldr r3,iAdrtablesPoi3  @ begin pointer area 3
    mov r4,#0    @ counter area 2
2:        @ r0 contains the first void item in area 3
    ldr r2,[r1,r4,lsl #2]    @ read string pointer address item r0 (4 bytes by pointer)
    cmp r2,#0                @ is null ?
    strne r2,[r3,r0,lsl #2]    @ no store pointer in area 3
    addne r0,#1             @ increment counter
    addne r4,#1             @ increment counter
    bne 2b                  @ and loop

	@ count items number in area 3
    ldr r1,iAdrtablesPoi3  @ begin pointer table
    mov r0,#0    @ counter
3:              @ begin loop
    ldr r2,[r1,r0,lsl #2]    @ read string pointer address item r0 (4 bytes by pointer)
    cmp r2,#0                @ is null ?
    addne r0,#1             @ no increment counter
    bne 3b                  @ and loop

    ldr r1,iAdrsZoneconv   @ conversion decimal
    bl conversion10S
    ldr r0,iAdrszMessLenArea
    bl affichageMess

100:   /* standard end of the program */
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call
iAdrtablesPoi1:		.int tablesPoi1
iAdrtablesPoi2:		.int tablesPoi2
iAdrtablesPoi3:		.int tablesPoi3
iAdrszMessLenArea:  .int szMessLenArea
iAdrsZoneconv:		.int  sZoneconv
iAdrszCarriageReturn:  .int  szCarriageReturn
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save  registres */
    push {r0,r1,r2,r7}    		/* save others registers */
    mov r2,#0   				/* counter length */
1:      	/* loop length calculation */
    ldrb r1,[r0,r2]  			/* read octet start position + index */
    cmp r1,#0       			/* if 0 its over */
    addne r2,r2,#1   			/* else add 1 in the length */
    bne 1b          			/* and loop */
                                /* so here r2 contains the length of the message */
    mov r1,r0        			/* address message in r1 */
    mov r0,#STDOUT      		/* code to write to the standard output Linux */
    mov r7, #WRITE             /* code call system "write" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7}     		/* restaur others registers */
    pop {fp,lr}    				/* restaur des  2 registres */
    bx lr	        			/* return  */

/***************************************************/
/*   conversion register signed décimal     */
/***************************************************/
/* r0 contient le registre   */
/* r1 contient l adresse de la zone de conversion */
conversion10S:
    push {r0-r5,lr}    /* save des registres */
    mov r2,r1       /* debut zone stockage */
    mov r5,#'+'     /* par defaut le signe est + */
    cmp r0,#0       /* nombre négatif ? */
    movlt r5,#'-'     /* oui le signe est - */
    mvnlt r0,r0       /* et inversion en valeur positive */
    addlt r0,#1
    mov r4,#10   /* longueur de la zone */
1: /* debut de boucle de conversion */
    bl divisionpar10 /* division  */
    add r1,#48        /* ajout de 48 au reste pour conversion ascii */
    strb r1,[r2,r4]  /* stockage du byte en début de zone r5 + la position r4 */
    sub r4,r4,#1      /* position précedente */
    cmp r0,#0
    bne 1b	       /* boucle si quotient different de zéro */
    strb r5,[r2,r4]  /* stockage du signe à la position courante */
    subs r4,r4,#1   /* position précedente */
    blt  100f         /* si r4 < 0  fin  */
    /* sinon il faut completer le debut de la zone avec des blancs */
    mov r3,#' '   /* caractere espace */
2:
    strb r3,[r2,r4]  /* stockage du byte  */
    subs r4,r4,#1   /* position précedente */
    bge 2b        /* boucle si r4 plus grand ou egal a zero */
100:  /* fin standard de la fonction  */
    pop {r0-r5,lr}   /*restaur desregistres */
    bx lr

/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 contient le dividende   */
/* r0 retourne le quotient */
/* r1 retourne le reste  */
divisionpar10:
  /* r0 contains the argument to be divided by 10 */
   push {r2-r4}   /* save registers  */
   mov r4,r0
   ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
   smull r1, r2, r3, r0   /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
   mov r2, r2, ASR #2     /* r2 <- r2 >> 2 */
   mov r1, r0, LSR #31    /* r1 <- r0 >> 31 */
   add r0, r2, r1         /* r0 <- r2 + r1 */
   add r2,r0,r0, lsl #2   /* r2 <- r0 * 5 */
   sub r1,r4,r2, lsl #1   /* r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10) */
   pop {r2-r4}
   bx lr                  /* leave function */
   bx lr                  /* leave function */
.Ls_magic_number_10: .word 0x66666667


arr1: [1 2 3]
arr2: ["four" "five" "six"]

print arr1 ++ arr2


(* The Rosetta Code array concatenation task, in ATS2. *)

(* In a way, the task is misleading: in a language such as ATS, one
   can always devise a very-easy-to-use array type, put the code for
   that in a library, and overload operators. Thus we can have
   "array1 + array2" as array concatenation in ATS, complete with
   garbage collection when the result no longer is needed.

   It depends on what libraries are in one's repertoire.

   Nevertheless, it seems fair to demonstrate how to concatenate two
   barebones arrays at the nitpicking lowest level, without anything
   but the barest contents of the ATS2 prelude. It will make ATS
   programming look difficult; but ATS programming *is* difficult,
   when you are using it to overcome the programming safety
   deficiencies of a language such as C, without losing the runtime
   efficiency of C code.

   What we want is the kind of routine that would be used *in the
   implementation* of "array1 + array2". So let us begin ... *)

#include "share/atspre_staload.hats" (* Loads some needed template
                                        code. *)

fn {t : [email protected]}

(* The demonstration will be for arrays of a non-linear type t. Were
   the arrays to contain a *linear* type ([email protected]), then either the old
   arrays would have to be destroyed or a copy procedure would be
   needed for the elements. *)

arrayconcat1 {m, n : nat}
             {pa, pb, pc : addr}
             (pfa  : !(@[t][m]) @ pa,
              pfb  : !(@[t][n]) @ pb,
              pfc  : !(@[t?][m + n]) @ pc >> @[t][m + n] @ pc |
              pa   : ptr pa,
              pb   : ptr pb,
              pc   : ptr pc,
              m    : size_t m,
              n    : size_t n) : void =

(* The routine takes as arguments three low-level arrays, passed by
   value, as pointers with associated views. The first array is of
   length m, with elements of type t, and the array must have been
   initialized; the second is a similar array of length n. The third
   array is uninitialized (thus the "?" character) and must have
   length m+n; its type will change to "initialized". *)

  {
    prval (pfleft, pfright) = array_v_split {t?} {pc} {m + n} {m} pfc

(* We have had to split the view of array c into a left part pfleft,
   of length m, and a right part pfright of length n. Arrays a and b
   will be copied into the respective parts of c. *)

    val _ = array_copy<t> (!pc, !pa, m)
    val _ = array_copy<t> (!(ptr_add<t> (pc, m)), !pb, n)

(* Copying an array *safely* is more complex than what we are doing
   here, but above the task has been given to the "array_copy"
   template in the prelude. The "!" signs appear because array_copy is
   call-by-reference but we are passing it pointers. *)

(* pfleft and pfright now refer to *initialized* arrays: one of length
   m, starting at address pc; the other of length n, starting at
   address pc+(m*sizeof<t>). *)

    prval _ = pfc := array_v_unsplit {t} {pc} {m, n} (pfleft, pfright)

(* Before we can exit, the view of array c has to be replaced. It is
   replaced by "unsplitting" the (now initialized) left and right
   parts of the array. *)

(* We are done. Everything should now work, and the result will be
   safe from buffer overruns or underruns, and against accidental
   misuse of uninitialized data. *)

  }

(* arrayconcat2 is a pass-by-reference interface to arrayconcat1. *)
fn {t : [email protected]}
arrayconcat2 {m, n : nat}
             (a    : &(@[t][m]),
              b    : &(@[t][n]),
              c    : &(@[t?][m + n]) >> @[t][m + n],
              m    : size_t m,
              n    : size_t n) : void =
  arrayconcat1 ([email protected] a, [email protected] b, [email protected] c |
                [email protected] a, [email protected] b, [email protected] c, m, n)

(* Overloads to let you say "arrayconcat" for either routine above. *)
overload arrayconcat with arrayconcat1
overload arrayconcat with arrayconcat2

implement
main0 () =

(* A demonstration program. *)

  let
    (* Some arrays on the stack. Because they are on the stack, they
       will not need explicit freeing. *)
    var a = @[int][3] (1, 2, 3)
    var b = @[int][4] (5, 6, 7, 8)
    var c : @[int?][7]

  in

    (* Compute c as the concatenation of a and b. *)
    arrayconcat<int> (a, b, c, i2sz 3, i2sz 4);

    (* The following simply prints the result. *)
    let
      (* Copy c to a linear linked list, because the prelude provides
         means to easily print such a list. *)
      val lst = array2list (c, i2sz 7)
    in
      println! (lst);      (* Print the list. *)
      free lst             (* The list is linear and must be freed. *)
    end
  end


List1 := [1, 2, 3]
List2 := [4, 5, 6]
cList := Arr_concatenate(List1, List2)
MsgBox % Arr_disp(cList) ; [1, 2, 3, 4, 5, 6]

Arr_concatenate(p*) {
    res := Object()
    For each, obj in p
        For each, value in obj
            res.Insert(value)
    return res
}

Arr_disp(arr) {
    for each, value in arr
        res .= ", " value
    return "[" SubStr(res, 3) "]"
}


_ArrayConcatenate($avArray, $avArray2)
Func _ArrayConcatenate(ByRef $avArrayTarget, Const ByRef $avArraySource, $iStart = 0)
	If Not IsArray($avArrayTarget) Then Return SetError(1, 0, 0)
	If Not IsArray($avArraySource) Then Return SetError(2, 0, 0)
	If UBound($avArrayTarget, 0) <> 1 Then
		If UBound($avArraySource, 0) <> 1 Then Return SetError(5, 0, 0)
		Return SetError(3, 0, 0)
	EndIf
	If UBound($avArraySource, 0) <> 1 Then Return SetError(4, 0, 0)

	Local $iUBoundTarget = UBound($avArrayTarget) - $iStart, $iUBoundSource = UBound($avArraySource)
	ReDim $avArrayTarget[$iUBoundTarget + $iUBoundSource]
	For $i = $iStart To $iUBoundSource - 1
		$avArrayTarget[$iUBoundTarget + $i] = $avArraySource[$i]
	Next

	Return $iUBoundTarget + $iUBoundSource
EndFunc   ;==>_ArrayConcatenate


#!/usr/bin/awk -f
BEGIN {
    split("cul-de-sac",a,"-")
    split("1-2-3",b,"-")
    concat_array(a,b,c)

    for (i in c) {
        print i,c[i]
    }
}

function concat_array(a,b,c, nc) {
    for (i in a) {
        c[++nc]=a[i]
    }
    for (i in b) {
       c[++nc]=b[i]
    }
}


DECLARE a[] = { 1, 2, 3, 4, 5 }
DECLARE b[] = { 6, 7, 8, 9, 10 }

DECLARE c ARRAY UBOUND(a) + UBOUND(b)

FOR x = 0 TO 4
    c[x] = a[x]
    c[x+5] = b[x]
NEXT


arraybase 1
global c

dimen = 5
dim a(dimen)
dim b(dimen)
# Array initialization
for i = 1 to dimen
	a[i] = i
	b[i] = i + dimen
next i

nt = ConcatArrays(a, b)

for i = 1 to nt
	print c[i];
	if i < nt then print ", ";
next i
end

function ConcatArrays(a, b)
	ta = a[?]
	tb = b[?]

	nt = ta + tb
	redim c(nt)

	for i = 1 to ta
		c[i] = a[i]
	next i
	for i = 1 to tb
		c[i + ta] = b[i]
	next i

	return nt
end function


#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \
  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));

void *array_concat(const void *a, size_t an,
                   const void *b, size_t bn, size_t s)
{
  char *p = malloc(s * (an + bn));
  memcpy(p, a, an*s);
  memcpy(p + an*s, b, bn*s);
  return p;
}

// testing
const int a[] = { 1, 2, 3, 4, 5 };
const int b[] = { 6, 7, 8, 9, 0 };

int main(void)
{
  unsigned int i;

  int *c = ARRAY_CONCAT(int, a, 5, b, 5);

  for(i = 0; i < 10; i++)
    printf("%d\n", c[i]);

  free(c);
  return EXIT_SUCCCESS;
}


using System;

namespace RosettaCode
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = { 1, 2, 3 };
            int[] b = { 4, 5, 6 };

            int[] c = new int[a.Length + b.Length];
            a.CopyTo(c, 0);
            b.CopyTo(c, a.Length);

            foreach(int n in c)
            {
                Console.WriteLine(n.ToString());
            }
        }
    }
}


shared void arrayConcatenation() {
	value a = Array {1, 2, 3};
	value b = Array {4, 5, 6};
	value c = concatenate(a, b);
	print(c);
}


       identification division.
       program-id. array-concat.

       environment division.
       configuration section.
       repository.
           function all intrinsic.

       data division.
       working-storage section.
       01 table-one.
          05 int-field pic 999 occurs 0 to 5 depending on t1.
       01 table-two.
          05 int-field pic 9(4) occurs 0 to 10 depending on t2.

       77 t1           pic 99.
       77 t2           pic 99.

       77 show         pic z(4).

       procedure division.
       array-concat-main.
       perform initialize-tables
       perform concatenate-tables
       perform display-result
       goback.

       initialize-tables.
           move 4 to t1
           perform varying tally from 1 by 1 until tally > t1
               compute int-field of table-one(tally) = tally * 3
           end-perform

           move 3 to t2
           perform varying tally from 1 by 1 until tally > t2
               compute int-field of table-two(tally) = tally * 6
           end-perform
       .

       concatenate-tables.
           perform varying tally from 1 by 1 until tally > t1
               add 1 to t2
               move int-field of table-one(tally)
                 to int-field of table-two(t2)
           end-perform
       .

       display-result.
           perform varying tally from 1 by 1 until tally = t2
               move int-field of table-two(tally) to show
               display trim(show) ", " with no advancing
           end-perform
           move int-field of table-two(tally) to show
           display trim(show)
       .

       end program array-concat.


# like in JavaScript
a = [1, 2, 3]
b = [4, 5, 6]
c = a.concat b


MODULE ArrayConcat;
IMPORT StdLog;

PROCEDURE Concat(x: ARRAY OF INTEGER; y: ARRAY OF INTEGER; OUT z: ARRAY OF INTEGER);
VAR
	i: INTEGER;
BEGIN
	ASSERT(LEN(x) + LEN(y) <= LEN(z));
	FOR i := 0 TO LEN(x) - 1 DO z[i] := x[i] END;
	FOR i := 0 TO LEN(y) - 1 DO z[i + LEN(x)] := y[i] END
END Concat;

PROCEDURE Concat2(x: ARRAY OF INTEGER;y: ARRAY OF INTEGER): POINTER TO ARRAY OF INTEGER;
VAR
	z: POINTER TO ARRAY OF INTEGER;
	i: INTEGER;
BEGIN
	NEW(z,LEN(x) + LEN(y));
	FOR i := 0 TO LEN(x) - 1 DO z[i] := x[i] END;
	FOR i := 0 TO LEN(y) - 1 DO z[i + LEN(x)] := y[i] END;
	RETURN z;
END Concat2;

PROCEDURE ShowArray(x: ARRAY OF INTEGER);
VAR
	i: INTEGER;
BEGIN
	i := 0;
	StdLog.Char('[');
	WHILE (i < LEN(x)) DO
		StdLog.Int(x[i]);IF i < LEN(x) - 1 THEN StdLog.Char(',') END;
		INC(i)
	END;
	StdLog.Char(']');StdLog.Ln;
END ShowArray;

PROCEDURE Do*;
VAR
	x: ARRAY 10 OF INTEGER;
	y: ARRAY 15 OF INTEGER;
	z: ARRAY 25 OF INTEGER;
	w: POINTER TO ARRAY OF INTEGER;
	i: INTEGER;
BEGIN
	FOR i := 0 TO LEN(x) - 1 DO x[i] := i END;
	FOR i := 0 TO LEN(y) - 1 DO y[i] := i END;
	Concat(x,y,z);StdLog.String("1> ");ShowArray(z);

	NEW(w,LEN(x) + LEN(y));
	Concat(x,y,z);StdLog.String("2:> ");ShowArray(z);

	StdLog.String("3:> ");ShowArray(Concat2(x,y));
END Do;

END ArrayConcat.


import std.stdio: writeln;

void main() {
    int[] a = [1, 2];
    int[] b = [4, 5, 6];

    writeln(a, " ~ ", b, " = ", a ~ b);
}


type
  TReturnArray = array of integer; //you need to define a type to be able to return it

function ConcatArray(a1,a2:array of integer):TReturnArray;
var
  i,r:integer;
begin
  { Low(array) is not necessarily 0 }
  SetLength(result,High(a1)-Low(a1)+High(a2)-Low(a2)+2); //BAD idea to set a length you won't release, just to show the idea!
  r:=0; //index on the result may be different to indexes on the sources
  for i := Low(a1) to High(a1) do begin
    result[r] := a1[i];
    Inc(r);
  end;
  for i := Low(a2) to High(a2) do begin
    result[r] := a2[i];
    Inc(r);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  a1,a2:array of integer;
  r1:array of integer;
  i:integer;
begin
  SetLength(a1,4);
  SetLength(a2,3);
  for i := Low(a1) to High(a1) do
    a1[i] := i;
  for i := Low(a2) to High(a2) do
    a2[i] := i;
  TReturnArray(r1) := ConcatArray(a1,a2);
  for i := Low(r1) to High(r1) do
    showMessage(IntToStr(r1[i]));
  Finalize(r1); //IMPORTANT!
  ShowMessage(IntToStr(High(r1)));
end;


var xs = [1,2,3]
var ys = [4,5,6]
var alls = Array.Concat(xs, ys)
print(alls)


;;;; VECTORS
(vector-append (make-vector 6 42) (make-vector 4 666))
    → #( 42 42 42 42 42 42 666 666 666 666)

;;;; LISTS
(append (iota 5) (iota 6))
   → (0 1 2 3 4 0 1 2 3 4 5)

;; NB - append may also be used with sequences (lazy lists)
(lib 'sequences)
   (take (append [1 .. 7] [7 6 .. 0]) #:all)
   → (1 2 3 4 5 6 7 6 5 4 3 2 1)


program ArrayConcatenation
    function main()
        a int[] = [ 1, 2, 3 ];
	b int[] = [ 4, 5, 6 ];
	c int[];
	c.appendAll(a);
	c.appendAll(b);

	for (i int from 1 to c.getSize())
	    SysLib.writeStdout("Element " :: i :: " = " :: c[i]);
	end
    end
end


import extensions;

public program()
{
    var a := new int[]{1,2,3};
    var b := new int[]{4,5};

    console.printLine(
        "(",a.asEnumerable(),") + (",b.asEnumerable(),
        ") = (",(a + b).asEnumerable(),")").readChar();
}


import Element exposing (show, toHtml)  -- elm-package install evancz/elm-graphics
import Html.App exposing (beginnerProgram)
import Array exposing (Array, append, initialize)

xs : Array Int
xs =
  initialize 3 identity  -- [0, 1, 2]

ys : Array Int
ys =
  initialize 3 <| (+) 3  -- [3, 4, 5]

main = beginnerProgram { model = ()
                       , view = \_ -> toHtml (show (append xs ys))
                       , update = \_ _ -> ()
                       }

-- Array.fromList [0,1,2,3,4,5]


PROGRAM ARRAY_CONCAT

DIM A[5],B[5],C[10]

!
! for rosettacode.org
!

BEGIN
  DATA(1,2,3,4,5)
  DATA(6,7,8,9,0)

  FOR I=1 TO 5 DO  ! read array A[.]
    READ(A[I])
  END FOR
  FOR I=1 TO 5 DO  ! read array B[.]
    READ(B[I])
  END FOR

  FOR I=1 TO 10 DO ! append B[.] to A[.]
    IF I>5 THEN
       C[I]=B[I-5]
     ELSE
       C[I]=A[I]
    END IF
    PRINT(C[I];)   ! print single C value
  END FOR

  PRINT

END PROGRAM


let a = [|1; 2; 3|]
let b = [|4; 5; 6;|]
let c = Array.append a b


#APPTYPE CONSOLE

DIM aint[] ={1, 2, 3}, astr[] ={"one", "two", "three"}, asng[] ={!1, !2, !3}

FOREACH DIM e IN ARRAYMERGE(aint, astr, asng)
	PRINT e, " ";
NEXT

PAUSE


program Concat_Arrays
  implicit none

  ! Note: in Fortran 90 you must use the old array delimiters (/ , /)
  integer, dimension(3) :: a = [1, 2, 3] ! (/1, 2, 3/)
  integer, dimension(3) :: b = [4, 5, 6] ! (/4, 5, 6/)
  integer, dimension(:), allocatable :: c, d

  allocate(c(size(a)+size(b)))
  c(1 : size(a)) = a
  c(size(a)+1 : size(a)+size(b)) = b
  print*, c

  ! alternative
  d = [a, b] ! (/a, b/)
  print*, d
end program Concat_Arrays


' FB 1.05.0 Win64

Sub ConcatArrays(a() As String, b() As String, c() As String)
   Dim aSize As Integer = UBound(a) - LBound(a) + 1
   Dim bSize As Integer = UBound(b) - LBound(b) + 1
   Dim cSize As Integer = aSize + bSize
   Redim c(0 To cSize - 1)
   Dim i As Integer
   For i = 0 To aSize - 1
     c(i) = a(LBound(a) + i)
   Next
   For i = 0 To bSize - 1
     c(UBound(a) + i + 1) = b(LBound(b) + i)
   Next
End Sub

Dim a(3) As String = {"The", "quick", "brown", "fox"}
Dim b(4) As String = {"jumped", "over", "the", "lazy", "dog"}
Dim c() As String
ConcatArrays(a(), b(), c())
For i As Integer = LBound(c) To UBound(c)
  Print c(i); " ";
Next
Print : Print
Print "Press any key to quit the program"
Sleep


arr1 = array( [1, 2, 3] )
arr2 = array( [4, 5, 6] )
arr3 = array( [7, 8, 9] )

println( arr1 + arr2 + arr3 )


void local fn DoIt
  CFArrayRef array = @[@"Alpha",@"Bravo",@"Charlie"]
  print array

  array = fn ArrayByAddingObjectsFromArray( array, @[@"Delta",@"Echo",@"FutureBasic"] )
  print array
end fn

window 1

fn DoIt

HandleEvents


Public Sub Main()
Dim sString1 As String[] = ["The", "quick", "brown", "fox"]
Dim sString2 As String[] = ["jumped", "over", "the", "lazy", "dog"]

sString1.Insert(sString2)

Print sString1.Join(" ")

End


[indent=4]
/*
   Array concatenation, in Genie
   Tectonics: valac array-concat.gs
*/

/* Creates a new array */
def int_array_concat(x:array of int, y:array of int):array of int
    var a = new Array of int(false, true, 0)  /* (zero-terminated, clear, size) */
    a.append_vals (x, x.length)
    a.append_vals (y, y.length)

    z:array of int = (owned) a.data
    return z

def int_show_array(a:array of int)
    for element in a do stdout.printf("%d ", element)
    stdout.printf("\n")

init
    x: array of int = {1, 2, 3}
    y: array of int = {3, 2, 1, 0, -1}
    z: array of int = int_array_concat(x, y)

    stdout.printf("x: "); int_show_array(x)
    stdout.printf("y: "); int_show_array(y)
    stdout.printf("z: "); int_show_array(z)
    print "%d elements in new array", z.length


#define array_concat(T,a1,a2,returned) \
    T[a1.length()+a2.length()] returned; \
    { \
    for(int i = 0; i < a1.length(); i++){ \
        returned[i] = a1[i]; \
    } \
    for(int i = 0; i < a2.length(); i++){ \
        returned[i+a1.length()] = a2[i]; \
    } \
}


package main

import "fmt"

func main() {
    // Example 1:  Idiomatic in Go is use of the append function.
    // Elements must be of identical type.
    a := []int{1, 2, 3}
    b := []int{7, 12, 60} // these are technically slices, not arrays
    c := append(a, b...)
    fmt.Println(c)

    // Example 2:  Polymorphism.
    // interface{} is a type too, one that can reference values of any type.
    // This allows a sort of polymorphic list.
    i := []interface{}{1, 2, 3}
    j := []interface{}{"Crosby", "Stills", "Nash", "Young"}
    k := append(i, j...) // append will allocate as needed
    fmt.Println(k)

    // Example 3:  Arrays, not slices.
    // A word like "array" on RC often means "whatever array means in your
    // language."  In Go, the common role of "array" is usually filled by
    // Go slices, as in examples 1 and 2.  If by "array" you really mean
    // "Go array," then you have to do a little extra work.  The best
    // technique is almost always to create slices on the arrays and then
    // use the copy function.
    l := [...]int{1, 2, 3}
    m := [...]int{7, 12, 60} // arrays have constant size set at compile time
    var n [len(l) + len(m)]int
    copy(n[:], l[:]) // [:] creates a slice that references the entire array
    copy(n[len(l):], m[:])
    fmt.Println(n)

}


var listA = { 1, 2, 3 }
var listB = { 4, 5, 6 }

var listC = listA.concat( listB )

print( listC ) // prints [1, 2, 3, 4, 5, 6]


def list = [1, 2, 3] + ["Crosby", "Stills", "Nash", "Young"]


REAL :: a(7), b(3), c(10)

c = a
DO i = 1, LEN(b)
   c(i + LEN(a)) = b(i)
ENDDO


 > a = [1,2,3]
 > b = [4,5,6]
 > help,a
      A               INT       = Array[3]
 > help,b
      B               INT       = Array[3]
 > print,a
      1       2       3
 > print,b
      4       5       6


Idris> [1, 2] ++ [4, 5, 6]
[1, 2, 3, 4, 5] : List Integer
Idris> :module Data.Vect
*Data/Vect> (the (Vect 2 Nat) [1, 2]) ++ (the (Vect 3 Nat) [3, 4, 5])
[1, 2, 3, 4, 5] : Vect 5 Nat


let A be {1, 2, 3};
let B be {4, 5, 6};
add B to A;


public static Object[] concat(Object[] arr1, Object[] arr2) {
    Object[] res = new Object[arr1.length + arr2.length];

    System.arraycopy(arr1, 0, res, 0, arr1.length);
    System.arraycopy(arr2, 0, res, arr1.length, arr2.length);

    return res;
}


a = [1,2,3]
b = [4,5,6]
ab = [a;b]
# the above bracket notation simply generates a call to vcat
ab = vcat(a,b)
# hcat is short for `horizontal concatenation`
ab = hcat(a,b) 	#ab -> 3x2 matrix
# the append!(a,b) method is mutating, appending `b` to `a`
append!(a,b)	# a now equals [1,2,3,4,5,6]


include ..\Utilitys.tlhy

( 1.0 "Hello" 3 2 / 4 2.1 power ) ( 5 6 7 8 ) chain print

" " input


fun main(args: Array<String>) {
    val a: Array<Int> = arrayOf(1, 2, 3) // initialise a
    val b: Array<Int> = arrayOf(4, 5, 6) // initialise b
    val c: Array<Int> = (a.toList() + b.toList()).toTypedArray()
    println(c)
}


local(arr1 = array(1, 2, 3))
local(arr2 = array(4, 5, 6))
local(arr3 = #arr1->asCopy)	//	make arr3 a copy of arr2
#arr3->merge(#arr2)		//	concatenate 2 arrays

Result:

arr1 = array(1, 2, 3)
arr2 = array(4, 5, 6)
arr3 = array(4, 5, 6)
arr3 = array(1, 2, 3, 4, 5, 6)


    x=10
    y=20
    dim array1(x)
    dim array2(y)

[concatenate]
    dim array3(x + y)
    for i = 1 to x
        array3(i) = array1(i)
    next
    for i = 1 to y
        array3(i + x) = array2(i)
    next

[print]
    for i = 1 to x + y
        print array3(i)
    next


##
  Array concatenation in LIL
##
set a [list 1 2 3]
set b [list 4 5 6]
set c [quote $a $b]

print $c
print "[index $c 0] [index $c 3]"


implement Command;

include "sys.m";
sys: Sys;

include "draw.m";

include "sh.m";

init(nil: ref Draw->Context, nil: list of string)
{
	sys = load Sys Sys->PATH;

	a := array[] of {1, 2};
	b := array[] of {3, 4, 5};

	c := array[len a + len b] of int;
	c[:] = a;
	c[len a:] = b;

	for (i := 0; i < len c; i++)
		sys->print("%d\n", c[i]);
}


a = [1,2]
b = [3,4,5]

repeat with v in b
  a.append(v)
end repeat

put a
-- [1, 2, 3, 4, 5]


to combine-arrays :a1 :a2
  output listtoarray sentence arraytolist :a1 arraytolist :a2
end
show combine-arrays {1 2 3} {4 5 6}   ; {1 2 3 4 5 6}


a = {1, 2, 3}
b = {4, 5, 6}

for _, v in pairs(b) do
    table.insert(a, v)
end

print(table.concat(a, ", "))


> A := Array( [ 1, 2, 3 ] );
                             A := [1, 2, 3]

> B := Vector['row']( [ sin( x ), cos( x ), tan( x ) ] );
                     B := [sin(x), cos(x), tan(x)]

> ArrayTools:-Concatenate( 1, A, B ); # stack vertically
                      [  1         2         3   ]
                      [                          ]
                      [sin(x)    cos(x)    tan(x)]

> ArrayTools:-Concatenate( 2, A, B ); # stack horizontally
                   [1, 2, 3, sin(x), cos(x), tan(x)]

> M := << a, b, c ; d, e, f >>; # a matrix
                                [a    b    c]
                           M := [           ]
                                [d    e    f]

> ArrayTools:-Concatenate( 1, M, A );
                             [a    b    c]
                             [           ]
                             [d    e    f]
                             [           ]
                             [1    2    3]


create a pair of arbitrary array:
    a:=matrix(2,2,max) b:=a+3

    a=|0 1|   b=|3 4|
      |1 1|     |4 4|

concatentate them vertically:
                 |0 1|
    stack(a,b) = |1 1|
                 |3 4|
                 |4 4|

    augment(a,b) = |0 1 3 4|
                   |1 1 3 4|


arrOne = [1, 2, 3]
arrTwo = [4, 5, 6]
print arrOne + arrTwo


/*
 Array concatenation, in Neko
*/

var a1 = $array(1,2,3,4)
var a2 = $array("abc", "def")

/* $array(a1, a2) creates an array of two arrays, $aconcat merges to one */
var ac = $aconcat($array(a1, a2))
$print(ac, "\n")


using System.Console;
using Nemerle.Collections;

module ArrayCat
{
    Main() : void
    {
        def arr1 = array[1, 2, 3]; def arr2 = array[4, 5, 6];
        def arr12 = arr1.Append(arr2);                       // <----
        foreach (i in arr12) Write($"$i  ");
    }
}


/* NetRexx */
options replace format comments java crossref nobinary

cymru =  [ 'Ogof Ffynnon Ddu', 'Ogof Draenen' ]

dlm = '-'.copies(40)

say dlm
loop c_ = 0 to cymru.length - 1
  say c_ cymru[c_]
  end c_

yorks = [ 'Malham Tarn Pot', 'Greygill Hole' ]

say dlm
loop y_ = 0 to yorks.length - 1
  say y_ yorks[y_]
  end y_

merge = ArrayList()
merge.addAll(Arrays.asList(cymru))
merge.addAll(Arrays.asList(yorks))

say dlm
merged = merge.toArray()
loop m_ = 0 to merged.length - 1
  say m_ merged[m_]
  end m_


; file:   arraycon.lsp
; url:    http://rosettacode.org/wiki/Array_concatenation
; author: oofoe 2012-01-28

(println "Append lists:  " (append '(3 a 5 3) (sequence 1 9)))

(println "Multi append:  "
         (append '(this is)
                 '(a test)
                 '(of the emergency)
                 (sequence 3 1)))

(println "Append arrays: "
         (append '((x 56) (b 99)) '((z 34) (c 23) (r 88))))

(exit)


MODULE ArrayConcat;
IMPORT
  Out;
TYPE
  IntArray = POINTER TO ARRAY OF INTEGER;
VAR
  x, y, z: IntArray;

  PROCEDURE InitArray(VAR x: IntArray;from: INTEGER);
  VAR
    i: LONGINT;
  BEGIN
    FOR i := 0 TO LEN(x^) - 1 DO
      x[i] := from;
      INC(from)
    END
  END InitArray;

  PROCEDURE Concat(x,y: IntArray; VAR z: IntArray);
  VAR
    i: LONGINT;
  BEGIN
    ASSERT(LEN(x^) + LEN(y^) <= LEN(z^));
    FOR i := 0 TO LEN(x^) - 1 DO z[i] := x[i] END;
    FOR i := 0 TO LEN(y^) - 1 DO z[i + LEN(x^)] := y[i] END
  END Concat;

  PROCEDURE Show(x: IntArray);
  VAR
    i: INTEGER;
  BEGIN
    i := 0;
    Out.Char('[');
    WHILE (i < LEN(x^)) DO
      Out.LongInt(x[i],3);IF i < LEN(x^) - 1 THEN Out.Char(',') END;
      INC(i)
    END;
    Out.Char(']');Out.Ln
  END Show;

BEGIN
  (* Standard types *)
  NEW(x,5);InitArray(x,1);
  NEW(y,10);InitArray(y,6);
  NEW(z,LEN(x^) + LEN(y^));

  Concat(x,y,z);
  Show(z)

END ArrayConcat.


bundle Default {
  class Arithmetic {
     function : Main(args : String[]) ~ Nil {
       array1 := [3, 5, 7];
       array2 := [2, 4, 6];

       array3 := Copy(array1, array2);
       each(i : array3) {
         array3[i]->PrintLine();
       };
  }

  function : native : Copy(array1 : Int[], array2 : Int[]) ~ Int[] {
     max := array1->Size() + array2->Size();
     array3 := Int->New[max];

     i := 0;
     for(i := i; i < array1->Size(); i += 1;) {
       array3[i] := array1[i];
     };

     j := 0;
     for(i := i; i < max; i += 1;) {
       array3[i] := array2[j];
       j += 1;
     };

      return array3;
    }
  }
}


NSArray *arr1 = @[@1, @2, @3];
NSArray *arr2 = @[@4, @5, @6];
NSArray *arr3 = [arr1 arrayByAddingObjectsFromArray:arr2];


# let list1 = [1; 2; 3];;
val list1 : int list = [1; 2; 3]
# let list2 = [4; 5; 6];;
val list2 : int list = [4; 5; 6]
# let list1and2 = list1 @ list2;;
val list1and2 : int list = [1; 2; 3; 4; 5; 6]


# With two arrays on the stack, cat pops
# them, concatenates them, and pushes the result back
# on the stack. This works with arrays of integers,
# strings, or whatever. For example,

[1 2 3] [4 5 6] cat # result: [1 2 3 4 5 6]
[`abc' `def'] [`ghi' `jkl'] cat # result: [`abc' `def' `ghi' `jkl']

# To concatenate more than two arrays, push the number of arrays
# to concatenate onto the stack and use ncat. For example,

[1 true `a'] [2 false `b'] [`3rd array'] 3 ncat
# leaves [1 true `a' 2 false `b' `3rd array'] on the stack


a = .array~of(1,2,3)
say "Array a has " a~items "items"
b = .array~of(4,5,6)
say "Array b has " b~items "items"
a~appendall(b)        -- adds all items from b to a
say "Array a now has " a~items "items"


'CREATE DYNAMIC ARRAY SPACES USING STRINGS

string sa=nuls 5* sizeof float
string sb=sa

'MAP ARRAY VARIABLES ONTO STRINGS

float a at *sa
float b at *sb

'ASSIGN SOME VALUES

a<=10,20,30,40,50
b<=60,70,80,90,00

'ADD ARRAY B TO A BY STRING CONCATENATION

sa+=sb

'TEST

print a[7] 'result 70


%% concatenating 2 lists
{Append [a b] [c d]} = [a b c d]

%% concatenating 2 tuples
{Tuple.append t(1 2 3) u(4 5 6)} = u(1 2 3 4 5 6)


BEGIN # find arithmetic numbers - numbers whose average divisor is an integer #
      # i.e. sum of divisors MOD count of divisors = 0                        #
    INT max number            = 500 000;    # maximum number we will consider #
    [ 1 : max number ]INT d sum;
    [ 1 : max number ]INT d count;
    # all positive integers are divisible by 1 and so have at least 1 divisor #
    FOR i TO max number DO d sum[ i ] := d count[ i ] := 1 OD;
    # construct the divisor sums and counts                                   #
    FOR i FROM 2 TO max number OVER 2 DO
        FOR j FROM i BY i TO max number DO
            d count[ j ] +:= 1;
            d sum[   j ] +:= i
        OD
    OD;
    # count arithmetic numbers, and show the first 100, the 1 000th, 10 000th #
    # and the 100 000th and show how many are composite                       #
    INT max arithmetic = 100 000;
    INT a count       := 0;
    INT c count       := 0;
    FOR i TO max number WHILE a count < max arithmetic DO
        IF d sum[ i ] MOD d count[ i ] = 0 THEN
            # have an arithmetic number                                       #
            IF d count[ i ] > 2 THEN
                # the number is composite                                     #
                c count +:= 1
            FI;
            a count +:= 1;
            IF a count <= 100 THEN
                print( ( " ", whole( i, -3 ) ) );
                IF a count MOD 10 = 0 THEN print( ( newline ) ) FI
            ELIF a count =   1 000
              OR a count =  10 000
              OR a count = 100 000
            THEN
                print( ( newline ) );
                print( ( "The ", whole( a count, 0 )
                       , "th arithmetic number is: ", whole( i, 0 )
                       , newline
                       )
                     );
                print( ( "    There are ", whole( c count, 0 )
                       , " composite arithmetic numbers up to ", whole( i, 0 )
                       , newline
                       )
                     )
            FI
        FI
    OD
END


LET n = 1
DO
   LET div = 1
   LET divcnt = 0
   LET sum = 0
   DO
      LET quot = n/div
      IF quot < div THEN EXIT DO
      IF REMAINDER(n, div) = 0 THEN
         IF quot = div THEN            !n IS a square
            LET sum = sum+quot
            LET divcnt = divcnt+1
            EXIT DO
         ELSE
            LET sum = sum+div+quot
            LET divcnt = divcnt+2
         END IF
      END IF
      LET div = div+1
   LOOP

   IF REMAINDER(sum, divcnt) = 0 THEN  !n IS arithmetic
      LET arithcnt = arithcnt+1
      IF arithcnt <= 100 THEN
         PRINT  USING "####": n;
         IF REMAINDER(arithcnt, 20) = 0 THEN PRINT
      END IF
      IF divcnt > 2 THEN LET compcnt = compcnt+1
      SELECT CASE arithcnt
      CASE 1000
           PRINT
           PRINT  USING "The #######th arithmetic number is #####,### up to which ###,### are composite.": arithcnt, n, compcnt
      CASE 10000, 100000, 1000000
           PRINT  USING "The #######th arithmetic number is #####,### up to which ###,### are composite.": arithcnt, n, compcnt
      CASE ELSE
           REM
      END SELECT
   END IF
   LET n = n+1
LOOP UNTIL arithcnt >= 1000000
END


#include <stdio.h>

void divisor_count_and_sum(unsigned int n, unsigned int* pcount,
                           unsigned int* psum) {
    unsigned int divisor_count = 1;
    unsigned int divisor_sum = 1;
    unsigned int power = 2;
    for (; (n & 1) == 0; power <<= 1, n >>= 1) {
        ++divisor_count;
        divisor_sum += power;
    }
    for (unsigned int p = 3; p * p <= n; p += 2) {
        unsigned int count = 1, sum = 1;
        for (power = p; n % p == 0; power *= p, n /= p) {
            ++count;
            sum += power;
        }
        divisor_count *= count;
        divisor_sum *= sum;
    }
    if (n > 1) {
        divisor_count *= 2;
        divisor_sum *= n + 1;
    }
    *pcount = divisor_count;
    *psum = divisor_sum;
}

int main() {
    unsigned int arithmetic_count = 0;
    unsigned int composite_count = 0;

    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {
        unsigned int divisor_count;
        unsigned int divisor_sum;
        divisor_count_and_sum(n, &divisor_count, &divisor_sum);
        if (divisor_sum % divisor_count != 0)
            continue;
        ++arithmetic_count;
        if (divisor_count > 2)
            ++composite_count;
        if (arithmetic_count <= 100) {
            printf("%3u ", n);
            if (arithmetic_count % 10 == 0)
                printf("\n");
        }
        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||
            arithmetic_count == 100000 || arithmetic_count == 1000000) {
            printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
            printf("Number of composite arithmetic numbers <= %u: %u\n", n,
                   composite_count);
        }
    }
    return 0;
}


1.0 "Hello" 3 2 / 4 2.1 power 4 tolist 5 6 7 8 4 tolist chain print


$arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);


go =>
   L1 = {1,2,3,4,5}, % define an array with {}
   L2 = {6,7,8,9},

   % The built-in array/list concatenation
   println(L1 ++ L2),

   % Using the built-in append/3 works only on lists
   % so the arrays must be converted to lists.
   append(L1.to_list,L2.to_list,L3),
   println(L3.to_array),
   nl.


[Int] array
array.append(1)
array.append(3)
array[0] = 2
print(array[0])  // retrieve first element in an array
print(array.last) // retrieve last element in an array
print(array.pop())  // pop last item in an array
print(array.pop(0)) // pop first item in an array

V size = 10
V myArray = [0] * size // create single-dimensional array
V width = 3
V height = 4
V myArray2 = [[0] * width] * height // create array of arrays


#include <cstdio>

void divisor_count_and_sum(unsigned int n,
			   unsigned int& divisor_count,
			   unsigned int& divisor_sum)
{
  divisor_count = 0;
  divisor_sum = 0;
  for (unsigned int i = 1;; i++)
  {
    unsigned int j = n / i;
    if (j < i)
      break;
    if (i * j != n)
      continue;
    divisor_sum += i;
    divisor_count += 1;
    if (i != j)
    {
      divisor_sum += j;
      divisor_count += 1;
    }
  }
}

int main()
{
  unsigned int arithmetic_count = 0;
  unsigned int composite_count = 0;

  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)
  {
    unsigned int divisor_count;
    unsigned int divisor_sum;
    divisor_count_and_sum(n, divisor_count, divisor_sum);
    unsigned int mean = divisor_sum / divisor_count;
    if (mean * divisor_count != divisor_sum)
      continue;
    arithmetic_count++;
    if (divisor_count > 2)
      composite_count++;
    if (arithmetic_count <= 100)
    {
      // would prefer to use <stream> and <format> in C++20
      std::printf("%3u ", n);
      if (arithmetic_count % 10 == 0)
	std::printf("\n");
    }
    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||
	(arithmetic_count == 100000) || (arithmetic_count == 1000000))
    {
      std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
      std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count);
    }
  }
  return 0;
}


USING: combinators formatting grouping io kernel lists
lists.lazy math math.functions math.primes math.primes.factors
math.statistics math.text.english prettyprint sequences
tools.memory.private ;

: arith? ( n -- ? ) divisors mean integer? ;
: larith ( -- list ) 1 lfrom [ arith? ] lfilter ;
: arith ( m -- seq ) larith ltake list>array ;
: composite? ( n -- ? ) dup 1 > swap prime? not and ;
: ordinal ( n -- str ) [ commas ] keep ordinal-suffix append ;

: info. ( n -- )
    {
        [ ordinal "%s arithmetic number: " printf ]
        [ arith dup last commas print ]
        [ commas "Number of composite arithmetic numbers <= %s: " printf ]
        [ drop [ composite? ] count commas print nl ]
    } cleave ;

"First 100 arithmetic numbers:" print
100 arith 10 group simple-table. nl
{ 3 4 5 6 } [ 10^ info. ] each


: (setq  A (1 2 3)  B '(a b c))
-> (a b c)
: (conc A B)                        # Concatenate lists in 'A' and 'B'
-> (1 2 3 a b c)
: A
-> (1 2 3 a b c)                    # Side effect: List in 'A' is modified!


int main() {
array arr1 = ({1, 2, 3});
array arr2 = ({4, 5, 6});
array arr3 = arr1 + arr2;
}


*        Arrays                    04/09/2015
ARRAYS   PROLOG
*        we use TA array with 1 as origin. So TA(1) to TA(20)
*        ta(i)=ta(j)
         L      R1,J               j
         BCTR   R1,0               -1
         SLA    R1,2               r1=(j-1)*4  (*4 by shift left)
         L      R0,TA(R1)          load r0 with ta(j)
         L      R1,I               i
         BCTR   R1,0               -1
         SLA    R1,2               r1=(i-1)*4  (*4 by shift left)
         ST     R0,TA(R1)          store r0 to ta(i)
         EPILOG
* Array of 20 integers (32 bits) (4 bytes)
TA       DS     20F
* Initialized array of 10 integers (32 bits)
TB       DC     10F'0'
* Initialized array of 10 integers (32 bits)
TC       DC     F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10'
* Array of 10 integers (16 bits)
TD       DS     10H
* Array of 10 strings of 8 characters (initialized)
TE       DC     10CL8' '
* Array of 10 double precision floating point reals (64 bits)
TF       DS     10D
*
I        DC     F'2'
J        DC     F'4'
         YREGS
         END    ARRAYS