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 conveyin... | #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 conveyin... | #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) ... | #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... |
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 ins... | #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... |
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 conveyin... | #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 conveyin... | #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) ... | #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 ... |
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 ins... | #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,
... |
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 conveyin... | #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 conveyin... | #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) ... | #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 ins... | #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) ... |
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 sy... |
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 conveyin... | #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 conveyin... | #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) ... | #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 ins... | #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
... |
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 ins... | #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' => 'gree... |
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 conveyin... | #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 conveyin... | #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: ");writ... |
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) ... | #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 ""]... |
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 ins... | #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),
... |
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 ins... | #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) ... | #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: [... |
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 ins... | #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())
fo... |
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) ... | #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 (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 ins... | #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');
... |
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) ... | #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 :li... |
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 ins... | #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_... |
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 ins... | #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 ... |
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) ... | #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... |
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 ins... | #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)... |
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) ... | #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() {... |
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 ins... | #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 ins... | #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) ... | #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 ins... | #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 ins... | #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) ... | #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
... |
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 ins... | #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) ... | #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... |
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 ins... | #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 ins... | #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) ... | #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("{... |
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 ins... | #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... |
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) ... | #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 {
... |
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 ins... | #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) ... | #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
}... |
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 ins... | #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 ins... | #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) ... | #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
c... |
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 ins... | #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 /* Displ... |
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 ins... | #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) ... | #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'
DECLAR... |
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 ins... | #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 m... |
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 ins... | #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) ... | #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++,=>... |
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 ins... | #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, 2... |
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 ins... | #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" e... |
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) ... | #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; ... |
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 ins... | #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 ins... | #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) ... | #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... |
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 ins... | #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 @:=... |
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 ins... | #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) ... | #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_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 ins... | #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) ... | #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 ins... | #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
... |
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 ins... | #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) ... | #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!"
... |
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 ins... | #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 ins... | #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 ins... | #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 ins... | #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... |
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 ins... | #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(H... |
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 ins... | #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 ins... | #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 ins... | #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 ins... | #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 ins... | #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... |
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 ins... | #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 ins... | #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=$(mktem... |
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 ins... | #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);... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.