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.
#Perl
Perl
# create array my @a = (1, 2, 3, 4, 5);   # create callback function sub mycallback { return 2 * shift; }   # use array indexing for (my $i = 0; $i < scalar @a; $i++) { print "mycallback($a[$i]) = ", mycallback($a[$i]), "\n"; }   # using foreach foreach my $x (@a) { print "mycallback($x) = ", mycallback($x), "\n"...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: dictType is hash [string] integer; var dictType: myDict is dictType.value;   const proc: main is func local var string: stri is ""; var integer: number is 0; begin myDict @:= ["hello"] 1; myDict @:= ["world"] 2; myDict @:= ["!"] 3;   # iterating over k...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#SenseTalk
SenseTalk
put {name:"Fluffy", type:"Rabbit", color:"White"} into animal put "Carries a watch" into animal's habits   put "The animal: " & animal put "The keys: " & keys of animal put "The values: " & animal's values // Keys and Values put ,"All Properties:" repeat with each [key,value] in animal put !"Key: [[key]] Value: [[val...
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...
#Plain_English
Plain English
To run: Start up. Demonstrate finding the arithmetic mean. Wait for the escape key. Shut down.   An entry is a thing with a fraction. A list is some entries. A sum is a fraction. A mean is a fraction.   To demonstrate finding the arithmetic mean: Create an example list. Write "A list: " then the example list on the con...
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...
#Pop11
Pop11
define mean(v); lvars n = length(v), i, s = 0; if n = 0 then return(0); else for i from 1 to n do s + v(i) -> s; endfor; endif; return(s/n); enddefine;
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Yabasic
Yabasic
sub floor(x) return int(x + .05) end sub   sub ceil(x) if x > int(x) x = x + 1 return x end sub   SUB ASort$(matriz$()) local last, gap, first, tempi$, tempj$, i, j   last = arraysize(matriz$(), 1)   gap = floor(last / 10) + 1 while(TRUE) first = gap + 1 for i = first to last tempi$ ...
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#zkl
zkl
var quickSelect=Import("quickSelect").qselect;   fcn median(xs){ n:=xs.len(); if (n.isOdd) return(quickSelect(xs,n/2)); ( quickSelect(xs,n/2-1) + quickSelect(xs,n/2) )/2; }
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Vala
Vala
  double arithmetic(int[] list){ double mean; double sum = 0; foreach(int number in list){ sum += number; } // foreach   mean = sum / list.length;   return mean; } // end arithmetic mean   double geometric(int[] list){ double mean; double product = 1; foreach(int number in list){ product *= number; } // f...
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) ...
#Perl
Perl
sub generate { my $n = shift; my $str = '[' x $n; substr($str, rand($n + $_), 0) = ']' for 1..$n; return $str; }   sub balanced { shift =~ /^ (\[ (?1)* \])* $/x; }   for (0..8) { my $input = generate($_); print balanced($input) ? " ok:" : "bad:", " '$input'\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...
#JavaScript
JavaScript
var assoc = {};   assoc['foo'] = 'bar'; assoc['another-key'] = 3;   // dot notation can be used if the property name is a valid identifier assoc.thirdKey = 'we can also do this!'; assoc[2] = "the index here is the string '2'";   //using JavaScript's object literal notation var assoc = { foo: 'bar', 'another-key': 3...
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.
#Phix
Phix
requires("0.8.2") function add1(integer x) return x + 1 end function ?apply({1,2,3},add1)
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.
#Phixmonti
Phixmonti
/# Rosetta Code problem: http://rosettacode.org/wiki/Apply_a_callback_to_an_array by Galileo, 05/2022 #/   include ..\Utilitys.pmt   def ++ 1 + enddef   def square dup * enddef   ( 1 2 3 ) dup   getid ++ map swap getid square map   pstack
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Sidef
Sidef
var hash = Hash.new( key1 => 'value1', key2 => 'value2', )   # Iterate over key-value pairs hash.each { |key, value| say "#{key}: #{value}"; }   # Iterate only over keys hash.keys.each { |key| say key; }   # Iterate only over values hash.values.each { |value| say value; }
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Slate
Slate
define: #pairs -> ({'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3} as: Dictionary). pairs keysAndValuesDo: [| :key :value | inform: '(k, v) = (' ; key printString ; ', ' ; value printString ; ')' ].   pairs keysDo: [| :key | inform: '(k, v) = (' ; key printString ; ', ' ; (pairs at: key) printString ; ')' ]...
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...
#PostScript
PostScript
  /findmean{ /x exch def /sum 0 def /i 0 def x length 0 eq {} { x length{ /sum sum x i get add def /i i 1 add def }repeat /sum sum x length div def }ifelse sum == }def  
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...
#PowerShell
PowerShell
function mean ($x) { if ($x.Count -eq 0) { return 0 } else { $sum = 0 foreach ($i in $x) { $sum += $i } return $sum / $x.Count } }
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Zoea
Zoea
  program: median case: 1 input: [4,5,6,8,9] output: 6 case: 2 input: [2,5,6] output: 5 case: 3 input: [2,5,6,8] output: 5.5  
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Zoea_Visual
Zoea Visual
  module Averages;   type Vector = array {math} * of real;   procedure Partition(var a: Vector; left, right: integer): integer; var pValue,aux: real; store,i,pivot: integer; begin pivot := right; pValue := a[pivot]; aux := a[right];a[right] := a[pivot];a[pivot] := aux; (* a[pivot] <-> a[right] *) store := left; ...
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#VBA
VBA
Private Function arithmetic_mean(s() As Variant) As Double arithmetic_mean = WorksheetFunction.Average(s) End Function Private Function geometric_mean(s() As Variant) As Double geometric_mean = WorksheetFunction.GeoMean(s) End Function Private Function harmonic_mean(s() As Variant) As Double harmonic_mean =...
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) ...
#Phix
Phix
with javascript_semantics function check_brackets(sequence s) integer level = 0 for i=1 to length(s) do switch s[i] case '[': level += 1 case ']': level -= 1 if level<0 then return false end if end switch end for return (level=0) end function 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...
#jq
jq
# An empty object: {}   # Its type: {} | type # "object"   # An object literal: {"a": 97, "b" : 98}   # Programmatic object construction: reduce ("a", "b", "c", "d") as $c ({}; . + { ($c) : ($c|explode[.0])} ) # {"a":97,"c":99,"b":98,"d":100}   # Same as above: reduce range (97;101) as $i ({}; . + { ([$i]|implode) : $...
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...
#Jsish
Jsish
var assoc = {};   assoc['foo'] = 'bar'; assoc['another-key'] = 3;   // dot notation can be used if the property name is a valid identifier assoc.thirdKey = 'we can also do this!'; assoc[2] = "the index here is the string '2'"; ;assoc;   //using JavaScript's object literal notation var assoc = { foo: 'bar', 'another...
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.
#PHP
PHP
function cube($n) { return($n * $n * $n); }   $a = array(1, 2, 3, 4, 5); $b = array_map("cube", $a); print_r($b);
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.
#Picat
Picat
go => L = 1..10,    % Using map/2 in different ways println(L.map(fun)), println(map(L,fun)), println(map(fun,L)),    % List comprehensions println([fun(I) : I in L]),    % Using apply/2 println([apply(fun,I) : I in L]),    % And using list comprehension with the function directly. pri...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Smalltalk
Smalltalk
|pairs| pairs := Dictionary from: { 'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3 }.   "iterate over keys and values" pairs keysAndValuesDo: [ :k :v | ('(k, v) = (%1, %2)' % { k. v }) displayNl ].   "iterate over keys" pairs keysDo: [ :key | ('key = %1, value = %2' % { key. pairs at: key }) displa...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#SNOBOL4
SNOBOL4
* # Create sample table t = table() t<'cat'> = 'meow' t<'dog'> = 'woof' t<'pig'> = 'oink'   * # Convert table to key/value array a = convert(t,'array')   * # Iterate pairs ploop i = i + 1; output = a<i,1> ' -> ' a<i,2> :s(ploop) * # Iterate keys kloop ...
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...
#Processing
Processing
float mean(float[] arr) { float out = 0; for (float n : arr) { out += n; } return out / arr.length; }
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...
#Prolog
Prolog
  mean(List, Mean) :- length(List, Length), sumlist(List, Sum), Mean is Sum / Length.  
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#zonnon
zonnon
  module Averages;   type Vector = array {math} * of real;   procedure Partition(var a: Vector; left, right: integer): integer; var pValue,aux: real; store,i,pivot: integer; begin pivot := right; pValue := a[pivot]; aux := a[right];a[right] := a[pivot];a[pivot] := aux; (* a[pivot] <-> a[right] *) store := left; ...
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#VBScript
VBScript
  Function arithmetic_mean(arr) sum = 0 For i = 0 To UBound(arr) sum = sum + arr(i) Next arithmetic_mean = sum / (UBound(arr)+1) End Function   Function geometric_mean(arr) product = 1 For i = 0 To UBound(arr) product = product * arr(i) Next geometric_mean = product ^ (1/(UBound(arr)+1)) End Function   Func...
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) ...
#Phixmonti
Phixmonti
"[[]][]" 0 var acc   len for get dup '[' == if acc 1 + var acc endif ']' == if acc 1 - var acc endif acc 0 < if exitfor endif endfor   print acc 0 < if " is NOT ok" else " is OK" endif 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...
#Julia
Julia
dict = Dict('a' => 97, 'b' => 98) # list keys/values # Dict{Char,Int64} with 2 entries: # 'b' => 98 # 'a' => 97   dict = Dict(c => Int(c) for c = 'a':'d') # dict comprehension # Dict{Char,Int64} with 4 entries: # 'b' => 98 # 'a' => 97 # 'd' => 100 # 'c' => 99   dict['é'] = 233; dict # add an element # Dict{...
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...
#K
K
/ creating an dictionary d1:.((`foo;1); (`bar;2); (`baz;3))   / extracting a value d1[`bar] 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.
#PicoLisp
PicoLisp
: (mapc println (1 2 3 4 5)) # Print numbers 1 2 3 4 5 -> 5   : (mapcar '((N) (* N N)) (1 2 3 4 5)) # Calculate squares -> (1 4 9 16 25)   : (mapcar ** (1 2 3 4 5) (2 .)) # Same, using a circular list -> (1 4 9 16 25)   : (mapcar if '(T NIL T NIL) '(1 2 3 4) '(5 6 7 8)) # Conditional function -> (1 6 3 8)
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.
#Pike
Pike
int cube(int n) { return n*n*n; }   array(int) a = ({ 1,2,3,4,5 }); array(int) b = cube(a[*]); // automap operator array(int) c = map(a, cube); // conventional map function
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Stata
Stata
mata // Create an associative array a=asarray_create() asarray(a,"one",1) asarray(a,"two",2)   // Loop over entries loc=asarray_first(a) do { printf("%s %f\n",asarray_key(a,loc),asarray_contents(a,loc)) loc=asarray_next(a,loc) } while(loc!=NULL) end
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Swift
Swift
let myMap = [ "hello": 13, "world": 31, "!"  : 71 ]   // iterating over key-value pairs: for (key, value) in myMap { println("key = \(key), value = \(value)") }
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...
#PureBasic
PureBasic
Procedure.d mean(List number()) Protected sum=0   ForEach number() sum + number() Next ProcedureReturn sum / ListSize(number()) ; Depends on programm if zero check needed, returns nan on division by zero EndProcedure
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...
#Python
Python
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Runtime.CompilerServices   Module Module1   <Extension()> Function Gmean(n As IEnumerable(Of Double)) As Double Return Math.Pow(n.Aggregate(Function(s, i) s * i), 1.0 / n.Count()) End Function   <Extension()> Function Hmean(n As IEnumerable(Of Double)) As Double Return...
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) ...
#PHP
PHP
#!/usr/bin/php <?php   # brackets generator function bgenerate ($n) { if ($n==0) return ''; $s = str_repeat('[', $n) . str_repeat(']', $n); return str_shuffle($s); }   function printbool($b) {return ($b) ? 'OK' : 'NOT OK';}   function isbalanced($s) { $bal = 0; for ($i=0; $i < strlen($s); $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 ins...
#Kotlin
Kotlin
fun main(args: Array<String>) { // map definition: val map = mapOf("foo" to 5, "bar" to 10, "baz" to 15, "foo" to 6)   // retrieval: println(map["foo"]) // => 6 println(map["invalid"]) // => null   // check keys: println("foo" in ma...
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.
#PL.2FI
PL/I
declare x(5) initial (1,3,5,7,8); x = sqrt(x); x = sin(x);
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.
#PL.2FSQL
PL/SQL
-- Let's create a generic class with one method to be used as an interface: CREATE OR REPLACE TYPE callback AS OBJECT ( -- A class needs at least one member even though we don't use it -- There's no generic OBJECT type, so let's call it NUMBER dummy NUMBER, -- Here's our function, and since PL/SQL doesn...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Tcl
Tcl
array set myAry { # list items here... }   # Iterate over keys and values foreach {key value} [array get myAry] { puts "$key -> $value" }   # Iterate over just keys foreach key [array names myAry] { puts "key = $key" }   # There is nothing for directly iterating over just the values # Use the keys+values ve...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#TXR
TXR
(defvarl h (hash))   (each ((k '(a b c)) (v '(1 2 3))) (set [h k] v))   (dohash (k v h) (put-line `@k -> @v`))
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...
#Q
Q
mean:{(sum x)%count x}
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...
#Quackery
Quackery
[ $ 'bigrat.qky' loadfile ] now!   [ [] swap times [ 20001 random 10000 - n->v 100 n->v v/ join nested join ] ] is makevector ( --> [ )   [ witheach [ unpack 2 point$ echo$ i 0 > if [ say ", " ] ] ] is echodecs ( [ --> )   [ dup size n->v rot...
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Vlang
Vlang
import math   fn main() { mut sum := 0.0 mut prod :=1.0 mut recip_sum := 0.0 n := 10   for val in 1..(n + 1) { sum += val prod *= val recip_sum = recip_sum + ( 1.0 / val ) }   a := sum / n g := math.pow( prod, ( 1.0 / f32(n) ) ) h := n / recip_sum   result...
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) ...
#Picat
Picat
go1 ?=> tests(Tests), member(Test,Tests), printf("%s: ", Test), ( balanced_brackets(Test) -> println("OK")  ; println("NOT OK") ), fail, nl. go1 => true.   % Check if a string of [] is balanced balanced_brackets(B) => C = 0, foreach(I in 1..B.length, C >= 0) C:= C + cond(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...
#Lambdatalk
Lambdatalk
    1) a (currently) reduced set of functions:   HASH: [5] [H.lib, H.new, H.disp, H.get, H.set!]   2) building an associative array: {def H key value | ...}   {def capitals {H.new nyk New York, United States | lon London, United Kingdom | par Paris, France | mos Moscou, Russia }} -> capitals  ...
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.
#Pop11
Pop11
;;; Define a procedure define proc(x); printf(x*x, '%p,'); enddefine;   ;;; Create array lvars ar = { 1 2 3 4 5};   ;;; Apply procedure to array appdata(ar, proc);
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.
#PostScript
PostScript
[1 2 3 4 5] { dup mul = } forall
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#UNIX_Shell
UNIX Shell
typeset -A a=([key1]=value1 [key2]=value2)   # just keys printf '%s\n' "${!a[@]}"   # just values printf '%s\n' "${a[@]}"   # keys and values for key in "${!a[@]}"; do printf '%s => %s\n' "$key" "${a[$key]}" done
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Vala
Vala
  using Gee;   void main(){ // declare HashMap var map = new HashMap<string, double?>();   // set 3 entries map["pi"] = 3.14; map["e"] = 2.72; map["golden"] = 1.62;   // iter...
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...
#R
R
omean <- function(v) { m <- mean(v) ifelse(is.na(m), 0, m) }
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...
#Racket
Racket
  #lang racket (require math)   (mean (in-range 0 1000)) ; -> 499 1/2 (mean '(2 2 4 4))  ; -> 3 (mean #(3 4 5 8))  ; -> 5  
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Wren
Wren
var rng = 1..10 var count = rng.count var A = rng.reduce { |acc, x| acc + x }/count var G = rng.reduce { |prod, x| prod * x}.pow(1/count) var H = rng.reduce { |acc, x| acc + 1/x}.pow(-1) * count   System.print("For the numbers %(rng):") System.print(" Arithmetic mean = %(A)") System.print(" Geometric mean = %(G)") S...
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) ...
#PicoLisp
PicoLisp
(load "@lib/simul.l") # For 'shuffle'   (de generateBrackets (N) (shuffle (make (do N (link "[" "]")))) )   (de checkBrackets (S) (let N 0 (for C S (if (= C "[") (inc 'N) (if2 (= C "]") (=0 N) (off N) (dec 'N) ) ) ) (=0 N) ) )   (for N 10...
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...
#Lang5
Lang5
: dip swap '_ set execute _ ; : nip swap drop ; : first 0 extract nip ; : second 1 extract nip ;   : assoc-in swap keys eq ; : assoc-index' over keys swap eq [1] index collapse ; : at swap assoc-index' subscript collapse second ; : delete-at swap assoc-index' first remove ; : keys 1 transpose first ; : set-at ...
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...
#langur
langur
var .hash = h{1: "abc", "1": 789}   # may assign with existing or non-existing hash key (if hash is mutable) .hash[7] = 49   writeln .hash[1] writeln .hash[7] writeln .hash["1"]   # using an alternate value in case of invalid index; prevents exception writeln .hash[1; 42] writeln .hash[2; 42]
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.
#PowerShell
PowerShell
1..5 | ForEach-Object { $_ * $_ }
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.
#Prolog
Prolog
?- assert((fun(X, Y) :- Y is 2 * X)). true.   ?- maplist(fun, [1,2,3,4,5], L). L = [2,4,6,8,10].  
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#VBA
VBA
Option Explicit Sub Test() Dim h As Object, i As Long, u, v, s Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3   'Iterate on keys For Each s In h.Keys Debug.Print s Next   'Iterate on values For Each s In h.Items Debug.Print s ...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#VBScript
VBScript
  'instantiate the dictionary object Set dict = CreateObject("Scripting.Dictionary")   'populate the dictionary or hash table dict.Add 1,"larry" dict.Add 2,"curly" dict.Add 3,"moe"   'iterate key and value pairs For Each key In dict.Keys WScript.StdOut.WriteLine key & " - " & dict.Item(key) Next  
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...
#Raku
Raku
multi mean([]){ Failure.new('mean on empty list is not defined') }; # Failure-objects are lazy exceptions multi mean (@a) { ([+] @a) / @a }
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...
#REBOL
REBOL
rebol [ Title: "Arithmetic Mean (Average)" URL: http://rosettacode.org/wiki/Average/Arithmetic_mean ]   average: func [v /local sum][ if empty? v [return 0]   sum: 0 forall v [sum: sum + v/1] sum / length? v ]   ; Note precision loss as spread increased.   print [mold x: [] "->" average x] print [mold x: [3...
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#XPL0
XPL0
include c:\cxpl\codes;   func real Power(X, Y); \X raised to the Y power real X, Y; \ (from StdLib.xpl) return Exp(Y * Ln(X));   int N, Order; real R, A, A1, G, G1, H, H1; [A1:= 0.0; G1:= 1.0; H1:= 0.0; Order:= true; for N:= 1 to 10 do [R:= float(N); \convert integer N ...
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) ...
#PL.2FI
PL/I
*process m or(!) s attributes source; cb: Proc Options(main); /* PL/I program to check for balanced brackets [] ******************** * 07.12.2013 Walter Pachl translated from REXX Version 2 *********************************************************************/ Dcl v Char(20) Var; Dcl (i,j) Bin Fixed(31); Dcl r 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...
#Lasso
Lasso
// In Lasso associative arrays are called maps   // Define an empty map local(mymap = map)   // Define a map with content local(mymap = map( 'one' = 'Monday', '2' = 'Tuesday', 3 = 'Wednesday' ))   // add elements to an existing map #mymap -> insert('fourth' = 'Thursday')   // retrieve a value from a map #mymap -> fi...
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.
#PureBasic
PureBasic
Procedure Cube(Array param.i(1)) Protected n.i For n = 0 To ArraySize(param()) Debug Str(param(n)) + "^3 = " + Str(param(n) * param(n) * param(n)) Next EndProcedure   Dim AnArray.i(4)   For n = 0 To ArraySize(AnArray()) AnArray(n) = Random(99) Next   Cube(AnArray())
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.
#Python
Python
def square(n): return n * n   numbers = [1, 3, 5, 7]   squares1 = [square(n) for n in numbers] # list comprehension   squares2a = map(square, numbers) # functional form   squares2b = map(lambda x: x*x, numbers) # functional form with `lambda`   squares3 = [n * n for n in numbers] # no nee...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Vim_Script
Vim Script
let dict = {"apples": 11, "oranges": 25, "pears": 4}   echo "Iterating over key-value pairs" for [key, value] in items(dict) echo key " => " value endfor echo "\n"   echo "Iterating over keys" for key in keys(dict) echo key endfor echo "\n"   echo "Iterating over values" for value in values(dict) echo value...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Vlang
Vlang
fn main() { my_map := { "hello": 13, "world": 31, "!"  : 71 }   // iterating over key-value pairs: for key, value in my_map { println("key = $key, value = $value") }   // iterating over keys: for key,_ in my_map { println("key = $key") }   // ite...
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...
#Red
Red
Red ["Arithmetic mean"]   print average [] print average [2 3 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...
#ReScript
ReScript
let arr = [3, 8, 4, 1, 5, 12]   let num = Js.Array.length(arr) let tot = Js.Array.reduce(\"+", 0, arr) let mean = float_of_int(tot) /. float_of_int(num)   Js.log(Js.Float.toString(mean))
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#zkl
zkl
ns:=T(1,2,3,4,5,6,7,8,9,10); ns.sum(0.0)/ns.len(); // Arithmetic mean ns.reduce('*,1.0).pow(1.0/ns.len()); // Geometric mean ns.len().toFloat() / ns.reduce(fcn(p,n){ p + 1.0/n },0.0); // Harmonic mean
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) ...
#PowerShell
PowerShell
  function Get-BalanceStatus ( $String ) { $Open = 0 ForEach ( $Character in [char[]]$String ) { switch ( $Character ) { "[" { $Open++ } "]" { $Open-- } default { $Open = -1 } } # If Open drops below zero (close bef...
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...
#LFE
LFE
  (let* ((my-dict (: dict new)) (my-dict (: dict store 'key-1 '"value 1" my-dict)) (my-dict (: dict store 'key-2 '"value 2" my-dict))) (: io format '"size: ~p~n" (list (: dict size my-dict))) (: io format '"some data: ~p~n" (list (: dict fetch 'key-1 my-dict))))    
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.
#QB64
QB64
  'Task 'Take a combined set of elements and apply a function to each element. 'UDT Type Friend Names As String * 8 Surnames As String * 8 Age As Integer End Type   Dim Friends(1 To 6) As Friend Restore FillArray SearchForAdult Friends(), LBound(friends), UBound(friends)   End   Data "John","Beoz",13,"Will"...
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.
#Quackery
Quackery
/O> [ 3 ** ] is cubed ( n --> n ) ...   Stack empty.   /O> ' [ 1 2 3 4 5 6 7 8 9 10 ] ... [] swap witheach ... [ cubed join ] ...   Stack: [ 1 8 27 64 125 216 343 512 729 1000 ]   /O> drop ...   Stack empty.   /O> ' [ 1 2 3 4 5 6 7 8 9 10 ] ... dup witheach ... [ cubed swap i^ poke ] ...   Stack: [ 1 8 27 64 ...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Wart
Wart
h <- (table 'a 1 'b 2) each (key val) table prn key " " val
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Wren
Wren
// create a new map with four entries var capitals = { "France": "Paris", "Germany": "Berlin", "Russia": "Moscow", "Spain": "Madrid" }   // iterate through the map and print out the key/value pairs for (c in capitals) System.print([c.key, c.value]) System.print()   // iterate though the map and print ou...
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...
#REXX
REXX
/*REXX program finds the averages/arithmetic mean of several lists (vectors) or CL input*/ parse arg @.1; if @.1='' then do; #=6 /*vector from the C.L.?*/ @.1 = 10 9 8 7 6 5 4 3 2 1 @.2 = 10 9 8 7 6 5 4 3 2 1 0 0 0 0 .11 ...
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) ...
#Prolog
Prolog
rosetta_brackets :- test_brackets([]), test_brackets(['[',']']), test_brackets(['[',']','[',']']), test_brackets(['[','[',']','[',']',']']), test_brackets([']','[']), test_brackets([']','[',']','[']), test_brackets(['[',']',']','[','[',']']).   balanced_brackets :- gen_bracket(2, B1, []), test_brackets(B1), g...
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...
#Liberty_BASIC
Liberty BASIC
  data "red", "255 50 50", "green", "50 255 50", "blue", "50 50 255" data "my fave", "220 120 120", "black", "0 0 0"   myAssocList$ =""   for i =1 to 5 read k$ read dat$ call sl.Set myAssocList$, k$, dat$ next i   print " Key 'green' is associated with data item "; sl.Get$( myAssocList$,...
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.
#R
R
cube <- function(x) x*x*x elements <- 1:5 cubes <- cube(elements)
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.
#Racket
Racket
  #lang racket   ;; using the `for/vector' comprehension form (for/vector ([i #(1 2 3 4 5)]) (sqr i))   ;; the usual functional `map' (vector-map sqr #(1 2 3 4 5))  
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#XPL0
XPL0
include c:\cxpl\stdlib; char Dict(10,10); int Entries;   proc AddEntry(Letter, Greek); \Insert entry into associative array char Letter, Greek; [Dict(Entries,0):= Letter; StrCopy(Greek, @Dict(Entries,1)); Entries:= Entries+1; \(limit checks ignored for simplicity) ];   int I; [Entries:= 0; AddEntry(^A, "a...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#zkl
zkl
var d=Dictionary("A","alpha","D","delta", "B","beta", "C", "gamma"); d.keys.pump(Console.print,fcn(k){String(k,",")}) d.values.apply("toUpper").println(); d.makeReadOnly(); // can only iterate over k,v pairs if read only foreach k,v in (d){print(k,":",v,"; ")}
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...
#Ring
Ring
  nums = [1,2,3,4,5,6,7,8,9,10] sum = 0 see "Average = " + average(nums) + nl   func average numbers for i = 1 to len(numbers) sum = sum + nums[i] next return sum/len(numbers)  
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...
#RPL.2F2
RPL/2
1 2 3 5 7 AMEAN << DEPTH DUP 'N' STO ->LIST ΣLIST N / >> 3.6
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) ...
#PureBasic
PureBasic
Procedure.s Generate(N) For i=1 To N sample$+"[]" Next For i=Len(sample$)-1 To 2 Step -1 r=Random(i-1)+1 If r<>i a.c=PeekC(@sample$+r*SizeOf(Character)) b.c=PeekC(@sample$+i*SizeOf(Character)) PokeC(@sample$+r*SizeOf(Character), b) PokeC(@sample$+i*SizeOf(Character), a) En...
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...
#Lingo
Lingo
props = [#key1: "value1", #key2: "value2"]   put props[#key2] -- "value2" put props["key2"] -- "value2" put props.key2 -- "value2" put props.getProp(#key2) -- "value2"
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...
#LiveCode
LiveCode
command assocArray local tArray put "value 1" into tArray["key 1"] put 123 into tArray["key numbers"] put "a,b,c" into tArray["abc"]   put "number of elements:" && the number of elements of tArray & return & \ "length of item 3:" && the length of tArray["abc"] & return & \ "keys:...
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.
#Raku
Raku
sub function { 2 * $^x + 3 }; my @array = 1 .. 5;   # via map function .say for map &function, @array;   # via map method .say for @array.map(&function);   # via for loop for @array { say function($_); }   # via the "hyper" metaoperator and method indirection say @array».&function;   # we neither need a variable fo...
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.
#Raven
Raven
# To print the squared elements [1 2 3 4 5] each dup * print
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...
#Ruby
Ruby
def mean(nums) nums.sum(0.0) / nums.size end   nums = [3, 1, 4, 1, 5, 9] nums.size.downto(0) do |i| ary = nums[0,i] puts "array size #{ary.size} : #{mean(ary)}" end
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...
#Run_BASIC
Run BASIC
print "Gimme the number in the array:";input numArray dim value(numArray) for i = 1 to numArray value(i) = i * 1.5 next   for i = 1 to total totValue = totValue +value(numArray) next if totValue <> 0 then mean = totValue/numArray print "The mean is: ";mean
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) ...
#Python
Python
>>> def gen(N): ... txt = ['[', ']'] * N ... random.shuffle( txt ) ... return ''.join(txt) ... >>> def balanced(txt): ... braced = 0 ... for ch in txt: ... if ch == '[': braced += 1 ... if ch == ']': ... braced -= 1 ... if braced < 0: return False ... ret...