task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#V
V
[1 2 3 4] [dup *] map
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#WDTE
WDTE
let s => import 'stream'; let a => import 'arrays';   let mean nums => a.stream nums -> s.reduce [0; 0] (@ s p n => [+ (a.at p 0) 1; + (a.at p 1) n]) -> (@ s p => / (a.at p 1) (a.at p 0));
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Wortel
Wortel
@let {  ; using a fork (sum divided-by length) mean1 @(@sum / #)    ; using a function with a named argument mean2 &a / @sum a #a   [[  !mean1 [3 1 4 1 5 9 2]  !mean2 [3 1 4 1 5 9 2] ]] }
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Simula
Simula
BEGIN INTEGER U; U := ININT; BEGIN   TEXT PROCEDURE GENERATE(N); INTEGER N; BEGIN INTEGER R; TEXT T; T :- NOTEXT; WHILE N > 0 DO BEGIN R := RANDINT(1,2,U); T :- T & (IF R = 1 THEN "[" ELSE "]"); N := N - 1; END; GENERATE :- T; END GENERATE;   BOOLEAN PROCEDURE BALANCED(T); TEXT T; BEGIN INTEGER LEVEL; CHARACTER BRACE; BOOLEAN DONE; T.SETPOS(1); WHILE T.MORE AND NOT DONE DO BEGIN BRACE := T.GETCHAR; IF BRACE = '[' THEN LEVEL := LEVEL + 1; IF BRACE = ']' THEN LEVEL := LEVEL - 1; IF LEVEL < 0 THEN DONE := TRUE; END; BALANCED := LEVEL = 0; END BALANCED;   INTEGER I,M; TEXT T; FOR I := 1 STEP 1 UNTIL 40 DO BEGIN M := RANDINT(0,10,U); T :- GENERATE(M); IF BALANCED(T) THEN OUTTEXT(" ") ELSE OUTTEXT(" NOT"); OUTTEXT(" BALANCED: "); OUTTEXT(T); OUTIMAGE; END;   END; END
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PARI.2FGP
PARI/GP
M = Map();
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#VBA
VBA
  Option Explicit   Sub Main() Dim arr, i 'init arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)   'Loop and apply a function (Fibonacci) to each element For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next   'return Debug.Print Join(arr, ", ") End Sub   Private Function Fibonacci(N) As Variant If N <= 1 Then Fibonacci = N Else Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2) End If End Function
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Wren
Wren
class Arithmetic { static mean(arr) { if (arr.count == 0) Fiber.abort("Length must be greater than zero") return arr.reduce(Fn.new{ |x,y| x+y }) / arr.count } } Arithmetic.mean([1,2,3,4,5]) // 3
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#XLISP
XLISP
(defun mean (v) (if (= (vector-length v) 0) nil (let ((l (vector->list v))) (/ (apply + l) (length l)))))
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Standard_ML
Standard ML
fun isBalanced s = checkBrackets 0 (String.explode s) and checkBrackets 0 [] = true | checkBrackets _ [] = false | checkBrackets ~1 _ = false | checkBrackets counter (#"["::rest) = checkBrackets (counter + 1) rest | checkBrackets counter (#"]"::rest) = checkBrackets (counter - 1) rest | checkBrackets counter (_::rest) = checkBrackets counter rest
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Perl
Perl
# 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', );
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#VBScript
VBScript
  class callback dim sRule   public property let rule( x ) sRule = x end property   public default function applyTo(a) dim p1 for i = lbound( a ) to ubound( a ) p1 = a( i ) a( i ) = eval( sRule ) next applyTo = a end function end class  
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Vim_Script
Vim Script
echo map([10, 20, 30], 'v:val * v:val') echo map([10, 20, 30], '"Element " . v:key . " = " . v:val') echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:val)') echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:key)')
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#XPL0
XPL0
code CrLf=9; code real RlOut=48;   func real Mean(A, N); real A; int N; real S; int I; [if N=0 then return 0.0; S:= 0.0; for I:= 0 to N-1 do S:= S+A(I); return S/float(N); ]; \Mean   real Test; [Test:= [1.0, 2.0, 5.0, -5.0, 9.5, 3.14159]; RlOut(0, Mean(Test, 6)); CrLf(0); ]
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#XSLT
XSLT
sum($values) div count($values)
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Stata
Stata
mata function random_brackets(n) { return(invtokens(("[","]")[runiformint(1,2*n,1,2)],"")) }   function is_balanced(s) { n = strlen(s) if (n==0) return(1) a = runningsum(92:-ascii(s)) return(all(a:>=0) & a[n]==0) } end
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Phix
Phix
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
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Visual_Basic_.NET
Visual Basic .NET
Module Program Function OneMoreThan(i As Integer) As Integer Return i + 1 End Function   Sub Main() Dim source As Integer() = {1, 2, 3}   ' Create a delegate from an existing method. Dim resultEnumerable1 = source.Select(AddressOf OneMoreThan)   ' The above is just syntax sugar for this; extension methods can be called as if they were instance methods of the first parameter. resultEnumerable1 = Enumerable.Select(source, AddressOf OneMoreThan)   ' Or use an anonymous delegate. Dim resultEnumerable2 = source.Select(Function(i) i + 1)   ' The sequences are the same. Console.WriteLine(Enumerable.SequenceEqual(resultEnumerable1, resultEnumerable2))   Dim resultArr As Integer() = resultEnumerable1.ToArray()   Array.ForEach(resultArr, AddressOf Console.WriteLine) End Sub End Module
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Yorick
Yorick
func mean(x) { if(is_void(x)) return 0; return x(*)(avg); }
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#zkl
zkl
fcn mean(a,b,c,etc){ z:=vm.arglist; z.reduce('+,0.0)/z.len() } mean(3,1,4,1,5,9); //-->3.83333 mean(); //-->Exception thrown: MathError(NaN (Not a number))
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Swift
Swift
import Foundation   func isBal(str: String) -> Bool {   var count = 0   return !str.characters.contains { ($0 == "["  ? ++count : --count) < 0 } && count == 0   }  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Phixmonti
Phixmonti
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  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PHP
PHP
$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
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Vorpal
Vorpal
A.map(F)
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Wart
Wart
map prn '(1 2 3 4 5)
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Zoea
Zoea
  program: average case: 1 input: [2,3,10] output: 5 case: 2 input: [7,11] output: 9  
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#zonnon
zonnon
  module Averages; type Vector = array {math} * of real;   procedure ArithmeticMean(x: Vector): real; begin (* sum is a predefined function for mathematical arrays *) return sum(x) end ArithmeticMean; var x: Vector;   begin x := new Vector(4); x := [1.0, 2.3, 3.2, 2.1, 5.3]; write("arithmetic mean: ");writeln(ArithmeticMean(x):10:2) end Averages.  
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Tcl
Tcl
proc generate {n} { if {!$n} return set l [lrepeat $n "\[" "\]"] set len [llength $l] while {$len} { set tmp [lindex $l [set i [expr {int($len * rand())}]]] lset l $i [lindex $l [incr len -1]] lset l $len $tmp } return [join $l ""] }   proc balanced s { set n 0 foreach c [split $s ""] { # Everything unmatched is ignored, which is what we want switch -exact -- $c { "\[" {incr n} "\]" {if {[incr n -1] < 0} {return false}} } } expr {!$n} }   for {set i 0} {$i < 15} {incr i} { set s [generate $i] puts "\"$s\"\t-> [expr {[balanced $s] ? {OK} : {NOT OK}}]" }
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Picat
Picat
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.  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PicoLisp
PicoLisp
(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
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#WDTE
WDTE
let a => import 'arrays'; let s => import 'stream';   let example => [3; 5; 2];   let double => a.stream example -> s.map (* 2) -> s.collect ;
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Wren
Wren
var arr = [1, 2, 3, 4, 5] arr = arr.map { |x| x * 2 }.toList arr = arr.map(Fn.new { |x| x / 2 }).toList arr.each { |x| System.print(x) }
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#TMG
TMG
program: readint(n) [n>0] readint(seed) loop: parse(render) [--n>0?]/done loop; render: random(i, 15) [i = (i+1)*2] loop2 = { 1 * }; loop2: random(b, 2) ( [b&1?] ={<[>} | ={<]>} ) [--i>0?]/done loop2 = { 2 1 }; done:  ;   /* Reads decimal integer */ readint: proc(n;i) string(spaces) [n=0] inta int1: [n = n*12+i] inta\int1; inta: char(i) [i<72?] [(i =- 60)>=0?];   /* LCG params: a = 29989, c = 28411, m = 35521 */ random: proc(r,mod) [seed = (seed*72445 + 67373) % 105301] [r = seed % mod] [r = r<0 ? -r : r];   spaces: << >>;   n: 0; i: 0; b: 0; seed: 0;
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Pike
Pike
  mapping m = ([ "apple": "fruit", 17: "seventeen" ]); write("indices: %O\nvalues: %O\n17: %O\n", indices(m), values(m), m[17]);  
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#XBS
XBS
func map(arr:array,callback:function){ set newArr:array = []; foreach(k,v as arr){ newArr[k]=callback(v,k,arr); } send newArr; }   set arr:array = [1,2,3,4,5]; set result:array = map(arr,func(v){ send v*2; });   log(arr.join(", ")); log(result.join(", "));
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Yabasic
Yabasic
sub map(f$, t()) local i   for i = 1 to arraysize(t(), 1) t(i) = execute(f$, t(i)) next i end sub   sub add1(x) return x + 1 end sub   sub square(x) return x * x end sub   dim t(10)   for i = 1 to 10 t(i) = i print t(i), "\t"; next i print   //map("add1", t()) map("square", t())   for i = 1 to 10 print t(i), "\t"; next i print
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT   SECTION gen_brackets values="[']",brackets="" LOOP n=1,12 brackets=APPEND (brackets,"","~") LOOP m=1,n a=RANDOM_NUMBERS (1,2,1),br=SELECT(values,#a) brackets=APPEND(brackets,"",br) b=RANDOM_NUMBERS (1,2,1),br=SELECT(values,#b) brackets=APPEND(brackets,"",br) ENDLOOP ENDLOOP brackets=SPLIT (brackets,":~:") ENDSECTION   MODE DATA $$ BUILD X_TABLE brackets=* [[[[ (4 ]]]] )4 [[[ (3 ]]] )3 [[ (2 ]] )2 [ (1 ] )1   $$ MODE TUSCRIPT DO gen_brackets LOOP b=brackets status=CHECK_BRACKETS (b,brackets,a1,e1,a2,e2) PRINT b," ",status ENDLOOP  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PL.2FI
PL/I
*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;
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Yacas
Yacas
Sin /@ {1, 2, 3, 4}   MapSingle(Sin, {1,2,3,4})   MapSingle({{x}, x^2}, {1,2,3,4})  
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Z80_Assembly
Z80 Assembly
Array: byte &01,&02,&03,&04,&05 Array_End:   foo: ld hl,Array ld b,Array_End-Array ;ld b,5   bar: inc (hl) inc (hl) inc (hl) inc hl ;next entry in array djnz bar
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#TXR
TXR
@(define paren)@(maybe)[@(coll)@(paren)@(until)]@(end)]@(end)@(end) @(do (defvar r (make-random-state nil))   (defun generate-1 (count) (let ((bkt (repeat "[]" count))) (cat-str (shuffle bkt))))   (defun generate-list (num count) [[generate tf (op generate-1 count)] 0..num])) @(next :list @(generate-list 22 6)) @(output) INPUT MATCHED REST @(end) @ (collect) @ (all) @parens @ (and) @{matched (paren)}@mismatched @ (end) @ (output) @{parens 15} @{matched 15} @{mismatched 15} @ (end) @(end)
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PL.2FSQL
PL/SQL
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; /
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Pop11
Pop11
;;; 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);
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Zig
Zig
pub fn main() !void { var array = [_]i32{1, 2, 3}; apply(@TypeOf(array[0]), array[0..], func); }   fn apply(comptime T: type, a: []T, f: fn(T) void) void { for (a) |item| { f(item); } }   fn func(a: i32) void { const std = @import("std"); std.debug.print("{d}\n", .{a-1}); }
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#zkl
zkl
L(1,2,3,4,5).apply('+(5))
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#TypeScript
TypeScript
// Balanced brackets   function isStringBalanced(str: string): bool { var paired = 0; for (var i = 0; i < str.length && paired >= 0; i++) { var c = str.charAt(i); if (c == '[') paired++; else if (c == ']') paired--; } return (paired == 0); }   function generate(n: number): string { var opensCount = 0, closesCount = 0; // Choose at random until n of one type generated var generated: string[] = new Array(); // Works like StringBuilder while (opensCount < n && closesCount < n) { if (Math.floor(Math.random() * 2) == 0) { ++opensCount; generated.push("["); } else { ++closesCount; generated.push("]"); } } // Now pad with the remaining other brackets generated.push(opensCount == n ? "]".repeat(n - closesCount) : "[".repeat(n - opensCount)); return generated.join(""); }   console.log("Supplied examples"); var tests: string[] = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"]; for (var test of tests) console.log(`The string '${test}' is ${(isStringBalanced(test) ? "OK." : "not OK.")); console.log(); console.log("Random generated examples"); for (var example = 0; example < 10; example++) { var test = generate(Math.floor(Math.random() * 10) + 1); console.log(`The string '${test}' is ${(isStringBalanced(test) ? "OK." : "not OK.")}`); }  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PostScript
PostScript
  <</a 100 /b 200 /c 300>> dup /a get =  
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#zonnon
zonnon
  module Main; type Callback = procedure (integer): integer; Vector = array {math} * of integer;   procedure Power(i:integer):integer; begin return i*i; end Power;   procedure Map(x: Vector;p: Callback): Vector; var i: integer; r: Vector; begin r := new Vector(len(x)); for i := 0 to len(x) - 1 do r[i] := p(i); end; return r end Map;   procedure Write(x: Vector); var i: integer; begin for i := 0 to len(x) - 1 do write(x[i]:4) end; writeln end Write;   var x,y: Vector;   begin x := [1,2,3,4,5]; Write(Map(x,Power)) end Main.  
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET a$="x+x" 20 LET b$="x*x" 30 LET c$="x+x^2" 40 LET f$=c$: REM Assign a$, b$ or c$ 150 FOR i=1 TO 5 160 READ x 170 PRINT x;" = ";VAL f$ 180 NEXT i 190 STOP 200 DATA 2,5,6,10,100  
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#UNIX_Shell
UNIX Shell
generate() { local b=() local i j tmp for ((i=1; i<=$1; i++)); do b+=( '[' ']') done for ((i=${#b[@]}-1; i>0; i--)); do j=$(rand $i) tmp=${b[j]} b[j]=${b[i]} b[i]=$tmp done local IFS= echo "${b[*]}" }   # a random number in the range [0,n) rand() { echo $(( $RANDOM % $1 )) }   balanced() { local -i lvl=0 local i for ((i=0; i<${#1}; i++)); do case ${1:i:1} in '[') ((lvl++));; ']') (( --lvl < 0 )) && return 1;; esac done (( lvl == 0 )); return $? }   for ((i=0; i<=10; i++)); do test=$(generate $i) balanced "$test" && result=OK || result="NOT OK" printf "%s\t%s\n" "$test" "$result" done
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Potion
Potion
mydictionary = (red=0xff0000, green=0x00ff00, blue=0x0000ff)   redblue = "purple" mydictionary put(redblue, 0xff00ff)   255 == mydictionary("blue") 65280 == mydictionary("green") 16711935 == mydictionary("purple")
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PowerShell
PowerShell
$hashtable = @{}
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Ursala
Ursala
#import std #import nat   balanced = @NiX ~&irB->ilZB ~&rh?/~&lbtPB ~&NlCrtPX   #cast %bm   main = ^(2-$'[]'*,balanced)* eql@ZFiFX*~ iota64
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Prolog
Prolog
  mymap(key1,value1). mymap(key2,value2).   ?- mymap(key1,V). V = value1  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PureBasic
PureBasic
NewMap dict.s() dict("country") = "Germany" Debug dict("country")
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#VBA
VBA
  Public Function checkBrackets(s As String) As Boolean 'function checks strings for balanced brackets Dim Depth As Integer Dim ch As String * 1   Depth = 0 For i = 1 To Len(s) ch = Mid$(s, i, 1) If ch = "[" Then Depth = Depth + 1 If ch = "]" Then If Depth = 0 Then 'not balanced checkBrackets = False Exit Function Else Depth = Depth - 1 End If End If Next checkBrackets = (Depth = 0) End Function   Public Function GenerateBrackets(N As Integer) As String 'generate a string with N opening and N closing brackets in random order Dim s As String Dim N2 As Integer, j As Integer Dim Brackets() As String * 1 Dim temp As String * 1   'catch trivial value If N <= 0 Then GenerateBrackets = "" Exit Function End If   N2 = N + N ReDim Brackets(1 To N2) For i = 1 To N2 Step 2 Brackets(i) = "[" Brackets(i + 1) = "]" Next i 'shuffle. For i = 1 To N2 j = 1 + Int(Rnd() * N2) 'swap brackets i and j temp = Brackets(i) Brackets(i) = Brackets(j) Brackets(j) = temp Next i 'generate string s = "" For i = 1 To N2 s = s & Brackets(i) Next i GenerateBrackets = s End Function   Public Sub BracketsTest() Dim s As String Dim i As Integer   For i = 0 To 10 s = GenerateBrackets(i) Debug.Print """" & s & """: "; If checkBrackets(s) Then Debug.Print " OK" Else Debug.Print " Not OK" Next End Sub  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Python
Python
hash = dict() # 'dict' is the dictionary type. hash = dict(red="FF0000", green="00FF00", blue="0000FF") hash = { 'key1':1, 'key2':2, } value = hash[key]
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#VBScript
VBScript
For n = 1 To 10 sequence = Generate_Sequence(n) WScript.Echo sequence & " is " & Check_Balance(sequence) & "." Next   Function Generate_Sequence(n) For i = 1 To n j = Round(Rnd()) If j = 0 Then Generate_Sequence = Generate_Sequence & "[" Else Generate_Sequence = Generate_Sequence & "]" End If Next End Function   Function Check_Balance(s) Set Stack = CreateObject("System.Collections.Stack") For i = 1 To Len(s) char = Mid(s,i,1) If i = 1 Or char = "[" Then Stack.Push(char) ElseIf Stack.Count <> 0 Then If char = "]" And Stack.Peek = "[" Then Stack.Pop End If Else Stack.Push(char) End If Next If Stack.Count > 0 Then Check_Balance = "Not Balanced" Else Check_Balance = "Balanced" End If End Function
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#R
R
> env <- new.env() > env[["x"]] <- 123 > env[["x"]]
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Racket
Racket
  #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  
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Private rand As New Random   Sub Main() For numInputs As Integer = 1 To 10 '10 is the number of bracket sequences to test. Dim input As String = GenerateBrackets(rand.Next(0, 5)) '5 represents the number of pairs of brackets (n) Console.WriteLine(String.Format("{0} : {1}", input.PadLeft(10, CChar(" ")), If(IsBalanced(input) = True, "OK", "NOT OK"))) Next Console.ReadLine() End Sub   Private Function GenerateBrackets(n As Integer) As String   Dim randomString As String = "" Dim numOpen, numClosed As Integer   Do Until numOpen = n And numClosed = n If rand.Next(0, 501) Mod 2 = 0 AndAlso numOpen < n Then randomString = String.Format("{0}{1}", randomString, "[") numOpen += 1 ElseIf rand.Next(0, 501) Mod 2 <> 0 AndAlso numClosed < n Then randomString = String.Format("{0}{1}", randomString, "]") numClosed += 1 End If Loop Return randomString End Function   Private Function IsBalanced(brackets As String) As Boolean   Dim numOpen As Integer = 0 Dim numClosed As Integer = 0   For Each character As Char In brackets If character = "["c Then numOpen += 1 If character = "]"c Then numClosed += 1 If numClosed > numOpen Then Return False End If Next Return numOpen = numClosed End Function End Module
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Raku
Raku
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;
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Vlang
Vlang
import datatypes as dt   fn is_valid(bracket string) bool { mut s := dt.Stack<string>{} for b in bracket.split('') { if b == '[' { s.push(b) } else { if s.peek() or {''} == '[' { s.pop() or {panic("WON'T GET HERE EVER")} } else { return false } } } return true }   fn main() { brackets := ['','[]','[][]','[[][]]','][','][][','[]][[]','[][[][[]][][[][]]]'] for b in brackets { println('$b ${is_valid(b)}') } }
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Raven
Raven
{ '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
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Wren
Wren
import "random" for Random   var isBalanced = Fn.new { |s| if (s.isEmpty) return true var countLeft = 0 // number of left brackets so far unmatched for (c in s) { if (c == "[") { countLeft = countLeft + 1 } else if (countLeft > 0) { countLeft = countLeft - 1 } else { return false } } return countLeft == 0 }   System.print("Checking examples in task description:") var brackets = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"] for (b in brackets) { System.write((b != "") ? b : "(empty)") System.print("\t  %(isBalanced.call(b) ? "OK" : "NOT OK")") } System.print("\nChecking 7 random strings of brackets of length 8:") var rand = Random.new() for (i in 1..7) { var s = "" for (j in 1..8) s = s + ((rand.int(2) == 0) ? "[" : "]") System.print("%(s)  %(isBalanced.call(s) ? "OK" : "NOT OK")") }
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Relation
Relation
  relation key, value insert "foo", "bar" insert "bar", "foo" insert "fruit", "apple" assert unique key print select key == "fruit" print  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Retro
Retro
with hashTable' hashTable constant table   table %{ first = 100 }% table %{ second = "hello, world!" keepString %}   table @" first" putn table @" second" puts
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#X86_Assembly
X86 Assembly
  section .data   MsgBalanced: db "OK", 10 MsgBalancedLen: equ 3   MsgUnbalanced: db "NOT OK", 10 MsgUnbalancedLen: equ 7   MsgBadInput: db "BAD INPUT", 10 MsgBadInputLen: equ 10   Open: equ '[' Closed: equ ']'   section .text   BalancedBrackets:   xor rcx, rcx mov rsi, rdi cld   processBracket: lodsb cmp al, 0 je determineBalance   cmp al, Open je processOpenBracket   cmp al, Closed je processClosedBracket   mov rsi, MsgBadInput mov rdx, MsgBadInputLen jmp displayResult   processOpenBracket: add rcx, 1 jmp processBracket   processClosedBracket: cmp rcx, 0 je unbalanced   sub rcx, 1 jmp processBracket     determineBalance: cmp rcx, 0 jne unbalanced   mov rsi, MsgBalanced mov rdx, MsgBalancedLen jmp displayResult   unbalanced: mov rsi, MsgUnbalanced mov rdx, MsgUnbalancedLen   displayResult: mov rax, 1 mov rdi, 1 syscall ret  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#REXX
REXX
/* 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 */
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Ring
Ring
  # Project Associative array/Creation   myarray = [["one",1], ["two",2], ["three",3]] see find(myarray,"two",1) + nl see find(myarray,2,2) + nl  
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#XBasic
XBasic
' Balanced brackets PROGRAM "balancedbrackets" VERSION "0.001"   IMPORT "xst"   DECLARE FUNCTION Entry() INTERNAL FUNCTION IsStringBalanced(str$) INTERNAL FUNCTION Generate$(n%%)   ' Pseudo-random number generator ' Based on the rand, srand functions from Kernighan & Ritchie's book ' 'The C Programming Language' DECLARE FUNCTION Rand() DECLARE FUNCTION SRand(seed%%)   FUNCTION Entry() PRINT "Supplied examples" DIM tests$[6] tests$[0] = "" tests$[1] = "[]" tests$[2] = "][" tests$[3] = "[][]" tests$[4] = "][][" tests$[5] = "[[][]]" tests$[6] = "[]][[]" FOR example@@ = 0 TO UBOUND(tests$[]) test$ = tests$[example@@] PRINT "The string '"; test$; "' is "; IFT IsStringBalanced(test$) THEN PRINT "OK." ELSE PRINT "not OK." END IF NEXT example@@ PRINT PRINT "Random generated examples" XstGetSystemTime (@msec) SRand(INT(msec) MOD 32768) FOR example@@ = 1 TO 10 test$ = Generate$(INT(Rand() / 32768.0 * 10.0) + 1) PRINT "The string '"; test$; "' is "; IFT IsStringBalanced(test$) THEN PRINT "OK." ELSE PRINT "not OK." END IF NEXT example@@ END FUNCTION   FUNCTION IsStringBalanced(s$) paired& = 0 i%% = 1 DO WHILE i%% <= LEN(s$) && paired& >= 0 c$ = MID$(s$, i%%, 1) SELECT CASE c$ CASE "[": INC paired& CASE "]": DEC paired& END SELECT INC i%% LOOP END FUNCTION (paired& = 0)   FUNCTION Generate$(n%%) opensCount%% = 0 closesCount%% = 0 ' Choose at random until n%% of one type generated generated$ = "" DO WHILE opensCount%% < n%% && closesCount%% < n%% SELECT CASE (INT(Rand() / 32768.0 * 2.0) + 1) CASE 1: INC opensCount%% generated$ = generated$ + "[" CASE 2: INC closesCount%% generated$ = generated$ + "]" END SELECT LOOP ' Now pad with the remaining other brackets IF opensCount%% = n%% THEN generated$ = generated$ + CHR$(']', n%% - closesCount%%) ELSE generated$ = generated$ + CHR$('[', n%% - opensCount%%) END IF END FUNCTION generated$   ' Return pseudo-random integer on 0..32767 FUNCTION Rand() #next&& = #next&& * 1103515245 + 12345 END FUNCTION USHORT(#next&& / 65536) MOD 32768   ' Set seed for Rand() FUNCTION SRand(seed%%) #next&& = seed%% END FUNCTION   END PROGRAM  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#RLaB
RLaB
  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.    
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Ruby
Ruby
hash={} hash[666]='devil' hash[777] # => nil hash[666] # => 'devil'
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#XBS
XBS
const Chars:[string] = ["[","]"]; func GenerateString(Amount:number=4):string{ set Result:string = ""; <|(*1..Amount)=>Result+=Chars[math.random(0,?Chars-1)]; send Result; }   func IsBalanced(String:string):boolean{ set Pairs:number = 0; <|(*(0..(?String-1)))=>(String::at(_)=="[")?(Pairs<0)?=>send false,Pairs++,=>Pairs--; send (Opens==Closes)&(Pairs==0); }   repeat 10 { set s = GenerateString(math.random(2,4)*2); log(`{s}: {IsBalanced(s)}`); }
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Rust
Rust
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); }
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Sather
Sather
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;  
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic code declarations   int N, I, C, Nest; char Str; [\Generate a string with N open brackets and N close brackets in arbitrary order N:= IntIn(0); \get number of brackets/2 from keyboard Str:= Reserve(2*N); for I:= 0 to 2*N-1 do Str(I):= ^[; C:= 0; \initialize count of "]" repeat I:= Ran(2*N); \change N random locations to "]" if Str(I) # ^] then [Str(I):= ^]; C:= C+1]; until C>=N;   \Determine whether string consists of nested pairs of open/close brackets I:= 0; C:= 0; Nest:= false; while I<2*N do [if Str(I) = ^[ then C:= C+1 else C:= C-1; if C<0 then Nest:= true; ChOut(0,Str(I)); I:= I+1; ]; ChOut(0,9\tab\); if Nest then Text(0,"NOT "); Text(0,"OK "); ]
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Scala
Scala
// 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
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Scheme
Scheme
(define my-dict '((a b) (1 hello) ("c" (a b c))) (assoc 'a my-dict) ; evaluates to '(a b)
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Ya
Ya
@Balanced[]s // each source must be started by specifying its file name; std extension .Ya could be ommitted and auto added by compiler   // all types are prefixed by ` // definition of anything new is prefixed by \, like \MakeNew_[]s and \len // MakeNew_[]s is Ok ident in Ya: _ starts sign part of ident, which must be ended by _ or alphanum `Char[^] \MakeNew_[]s(`Int+ \len) // `Char[^] and `Char[=] are arrays that owns their items, like it's usally in other langs; // yet in assignment of `Char[^] to `Char[=] the allocated memory is moved from old to new owner, and old string becomes empty // there are tabs at starts of many lines; these tabs specify what in C++ is {} blocks, just like in Python len & 1 ==0 ! // it's a call to postfix function '!' which is an assert: len must be even `Char[=] \r(len) // allocate new string of length len // most statements are analogous to C++ but written starting by capital letter: For If Switch Ret For `Char[] \eye = r; eye // // `Char[] is a simplest array of chars, which does not hold a memory used by array items; inc part of For loop is missed: it's Ok, and condition and init could also be missed *eye++ = '['; *eye++ = '[' // fill r by "[][][]...". The only place with ; as statement delemiter: required because the statement is not started at new line. // below is a shuffle of "[][][]..." array For `Char[] \eye = r; ++eye // var eye is already defined, but being the same `Char[] it's Ok by using already exisiting var. ++eye is used: it allows use of eye[-1] inside `Int+ \at = Random(eye/Length) // `Int+ is C++'s unsigned int. eye/Length: / is used for access to field, like in file path eye[-1],eye[at] = eye[at],eye[-1] // swap using tuples; eye[-1] accesses char that is out of current array, yet it's allowed Ret r // Ret is C's return `Bool \AreBalanced(`Char[] \brackets) `Int+ \extra = 0 For ;brackets ;++brackets Switch *brackets '[' // it's a C++'s 'case': both 'case' and ':' are skipped being of no value; but the code for a case should be in block, which is here specifyed by tabs at next line start ++extra ']' If !!extra // '!!' is `Bool not, like all other `Bool ops: && || ^^ Ret No // No and False are C's false; Yes and True are C's true --extra // There is no default case, which is written as ':' - so if no case is Ok then it will fail just like if being written as on the next line // : { 0! } // C's default: assert(0); Ret extra == 0 // function ala 'main' is not used: all global code from all modules are executed; so below is what typically is in ala 'main' For `Int \n=10; n; --n // below note that new var 'brackets' is created inside args of func call //@Std/StdIO/ is used here to use Print function; else it maybe changed to Use @Std/StdIO at global level before this For loop @Std/StdIO/Print(; "%s : %s\n" ;`Char[=] \brackets = MakeNew_[]s(10) /* all bracket strings are of length 10 */; AreBalanced(brackets) ? "Ok" : "bad") // note that starting arg of Print is missed by using ';' - default arg value is allowed to use for any arg, even if next args are written
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Seed7
Seed7
$ 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;
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#SenseTalk
SenseTalk
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  
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Yabasic
Yabasic
sub check_brackets(s$) local level, i   for i = 1 to len(s$) switch mid$(s$, i, 1) case "[": level = level + 1 : break case "]": level = level - 1 : if level < 0 break 2 end switch next i return level = 0 end sub   s$ = "[[]][]"   print s$, " = ";   if not check_brackets(s$) print "not "; print "ok"
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#SETL
SETL
m := {['foo', 'a'], ['bar', 'b'], ['baz', 'c']};
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#zkl
zkl
fcn bb(bs){ while(a:=bs.span("[","]")) {bs=bs[a[1],*]} (Void!=a) }
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#SETL4
SETL4
  * 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  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Sidef
Sidef
var hash = Hash.new( key1 => 'value1', key2 => 'value2', );   # Add a new key-value pair hash{:key3} = 'value3';
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 FOR n=1 TO 7 20 READ s$ 25 PRINT "The sequence ";s$;" is "; 30 GO SUB 1000 40 NEXT n 50 STOP 1000 LET s=0 1010 FOR k=1 TO LEN s$ 1020 LET c$=s$(k) 1030 IF c$="[" THEN LET s=s+1 1040 IF c$="]" THEN LET s=s-1 1050 IF s<0 THEN PRINT "Bad!": RETURN 1060 NEXT k 1070 IF s=0 THEN PRINT "Good!": RETURN 1090 PRINT "Bad!" 1100 RETURN 2000 DATA "[]","][","][][","[][]","[][][]","[]][[]","[[[[[]]]]][][][]][]["  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Slate
Slate
Dictionary new*, 'MI' -> 'Michigan', 'MN' -> 'Minnesota'
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Smalltalk
Smalltalk
states := Dictionary new. states at: 'MI' put: 'Michigan'. states at: 'MN' put: 'Minnesota'.
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#SNOBOL4
SNOBOL4
t = table() t<"red"> = "#ff0000" t<"green"> = "#00ff00" t<"blue"> = "#0000ff"   output = t<"red"> output = t<"blue"> output = t<"green"> end
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#SQL
SQL
  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';  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#SQL_PL
SQL PL
  --#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@  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Stata
Stata
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
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Swift
Swift
// 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]
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Symsyn
Symsyn
  #+ 'name=bob' $hash | add to hash #? 'name' $hash $S | find 'name' and return 'bob' in $S #- 'name' $hash | delete 'name=bob' from hash  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Tcl
Tcl
# 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) }
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Toka
Toka
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 .
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#UNIX_Shell
UNIX Shell
typeset -A hash hash=( [key1]=val1 [key2]=val2 ) hash[key3]=val3 echo "${hash[key3]}"
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#UnixPipes
UnixPipes
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
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Vala
Vala
  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")); }