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/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Nim
Nim
import re import strutils   let r = re"(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)"   #---------------------------------------------------------------------------------------------------   proc commatize(str: string; startIndex = 0; period = 3; sep = ","): string =   result = str var dp, ip = ""   if startIndex notin 0....
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Perl
Perl
@input = ( ['pi=3.14159265358979323846264338327950288419716939937510582097494459231', ' ', 5], ['The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', '.'], ['-in Aus$+1411.8millions'], ['===US$0017440 millions=== (in 2000 dollars)'], ['123.e8000 is pretty big.'], ['The land area...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#COBOL
COBOL
identification division. program-id. CompareLists.   data division. working-storage section. 78 MAX-ITEMS value 3. 77 i pic 9(2). 01 the-list. 05 list-items occurs MAX-ITEMS. 10 list-item pic x(3). ...
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#ALGOL_W
ALGOL W
begin    % returns a list of the words contained in wordString, separated by ", ", %  % except for the last which is separated from the rest by " and ".  %  % The words are enclosed by braces  % string(256) procedure toList ( string(256) value words ) ; begi...
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#AppleScript
AppleScript
-- quibble :: [String] -> String on quibble(xs) if length of xs > 1 then set applyCommas to ¬ compose([curry(my intercalate)'s |λ|(", "), my |reverse|, my tail])   intercalate(" and ", ap({applyCommas, my head}, {|reverse|(xs)})) else concat(xs) end if end quibble   -- TE...
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#AutoHotkey
AutoHotkey
;=========================================================== ; based on "https://www.geeksforgeeks.org/combinations-with-repetitions/" ;=========================================================== CombinationRepetition(arr, k:=0, Delim:="") { CombinationRepetitionUtil(arr, k?k:str.count(), Delim, [k+1], result:=[]) re...
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at P...
#Crystal
Crystal
require "big" include Math   struct Int   def permutation(k) (self-k+1..self).product(1.to_big_i) end   def combination(k) self.permutation(k) // (1..k).product(1.to_big_i) end   def big_permutation(k) exp(lgamma_plus(self) - lgamma_plus(self-k)) end   def big_combination(k) exp( lgamma_p...
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#C.23
C#
  using System; using System.IO; using System.Linq; using System.Collections.Generic;     namespace Rosetta {   public enum TokenType { End_of_input, Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract, Op_negate, Op_not, Op_less, Op_lessequal, Op_greater, Op_greaterequal, Op_equal, Op_noteq...
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#BASIC
BASIC
PRINT "args: '"; COMMAND$; "'"
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion   set Count=0 :loop if not "%1"=="" ( set /a count+=1 set parameter[!count!]=%1 shift goto loop )   for /l %%a in (1,1,%count%) do ( echo !parameter[%%a]! )
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#ALGOL_68
ALGOL 68
£ This is a hash/pound comment for a UK keyboard £
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#ALGOL_W
ALGOL W
begin comment a comment;  % another comment  ;  % and another  % end this_word_is_also_a_comment.
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#Nim
Nim
import os, parseutils, strutils, strscans, strformat   type   Value = int32 BytesValue = array[4, byte] Address = int32   OpCode = enum opFetch = "fetch" opStore = "store" opPush = "push" opJmp = "jmp" opJz = "jz" opAdd = "add" opSub =...
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#M2000_Interpreter
M2000 Interpreter
  Module CodeGenerator (s$){ Function code$(op$) { =format$("{0::-6} {1}", pc, op$) pc++ } Function code2$(op$, n$) { =format$("{0::-6} {1} {2}", pc, op$, n$) pc+=5 } Function code3$(op$,pc, st, ed) { =format$("{0::-6} {1} ({2}) {3}", pc, op$, ed-st-1, ed) }   Enum tok { gneg, gnot, gmul, gdiv, gmod,...
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Python
Python
def builtinsort(x): x.sort()   def partition(seq, pivot): low, middle, up = [], [], [] for x in seq: if x < pivot: low.append(x) elif x == pivot: middle.append(x) else: up.append(x) return low, middle, up import random def qsortranpart(seq): size = l...
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#REXX
REXX
/*REXX pgm compares various sorts for 3 types of input sequences: ones/ascending/random.*/ parse arg ranges start# seed . /*obtain optional arguments from the CL*/ if ranges=='' | ranges=="," then ranges= 5 /*Not Specified? Then use the default.*/ if start#=='' | start#=="," then start#= 250...
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Lambdatalk
Lambdatalk
  {def L.new {lambda {:s} {if {S.empty? {S.rest :s}} then {P.new {S.first :s} nil} else {P.new {S.first :s} {L.new {S.rest :s}}}}}} -> L.new   {def L.disp {lambda {:l} {if {W.equal? :l nil} then else {br} {W.length {P.left :l}} : {P.left :l} {L.disp {P.right :l}}}}} -> L.disp  
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Lua
Lua
function test(list) table.sort(list, function(a,b) return #a > #b end) for _,s in ipairs(list) do print(#s, s) end end test{"abcd", "123456789", "abcdef", "1234567"}
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read in...
#Python
Python
from __future__ import print_function import sys, shlex, operator   tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \ tk_Geq, tk_Eql, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \ tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_C...
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Delphi
Delphi
  program game_of_life;   {$APPTYPE CONSOLE}       uses System.SysUtils, Velthuis.Console; // CrlScr   type TBoolMatrix = TArray<TArray<Boolean>>;   TField = record s: TBoolMatrix; w, h: Integer; procedure SetValue(x, y: Integer; b: boolean); function Next(x, y: Integer): boolean; function S...
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Ring
Ring
  see new point {x=10 y=20} class point x y  
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Ruby
Ruby
Point = Struct.new(:x,:y) pt = Point.new(6,7) puts pt.x #=> 6 pt.y = 3 puts pt #=> #<struct Point x=6, y=3>   # The other way of accessing pt = Point[2,3] puts pt[:x] #=> 2 pt['y'] = 5 puts pt #=> #<struct Point x=2, y=5>   pt.each_pair{|member, value| puts "#{member} : #{value}"} ...
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#BASIC256
BASIC256
# Begin Case / Case / End Case, Do / Until, If Then, While / End While begin case case boolean_expr statement(s) case boolean_expr statement(s) else statement(s) end case do statement(s) until boolean_expr if booleanexpr then statement(s) end if if booleanexpr then statem...
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Phix
Phix
with javascript_semantics procedure commatize(string s, sep=",", integer start=1, step=3) integer l = length(s) for i=start to l do if find(s[i],"123456789") then for j=i+1 to l+1 do if j>l or not find(s[j],"0123456789") then for k=j-1-step to i by -step d...
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Python
Python
  import re as RegEx     def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ): outString = "" strPos = 0 matches = RegEx.findall( "[0-9]*", _string )   for match in matches[:-1]: if not match: outString += _string[ strPos ] strPos += 1 else: if len(match) > _periodLen: leadIn = match...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Common_Lisp
Common Lisp
  (defun strings-equal-p (strings) (null (remove (first strings) (rest strings) :test #'string=)))   (defun strings-ascending-p (strings) (loop for string1 = (first strings) then string2 for string2 in (rest strings) always (string-lessp string1 string2)))  
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#D
D
void main() { import std.stdio, std.algorithm, std.range, std.string;   foreach (const strings; ["AA AA AA AA", "AA ACB BB CC"].map!split) { strings.writeln; strings.zip(strings.dropOne).all!(ab => ab[0] == ab[1]).writeln; strings.zip(strings.dropOne).all!(ab => ab[0] < ab[1]).writeln; ...
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Arturo
Arturo
quibble: function [seq][ if? 0=size seq -> "{}" else [ if? 1=size seq -> "{" ++ seq\0 ++ "}" else -> "{" ++ (join.with:", " slice seq 0 (size seq)-1) ++ " and " ++ (last seq) ++ "}" ] ]   sentences: [ [] ["ABC"] ["ABC" "DEF"] ["ABC" "DEF" "G" "H"] ]   loop sentences 'sentence [ print quibble sentence ]
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#AWK
AWK
  # syntax: GAWK -f COMBINATIONS_WITH_REPETITIONS.AWK BEGIN { n = split("iced,jam,plain",donuts,",") for (i=1; i<=n; i++) { for (j=1; j<=n; j++) { if (donuts[i] < donuts[j]) { key = sprintf("%s %s",donuts[i],donuts[j]) } else { key = sprintf("%s %s",donuts[j],do...
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at P...
#D
D
import std.stdio, std.mathspecial, std.range, std.algorithm, std.bigint, std.conv;   enum permutation = (in uint n, in uint k) pure => reduce!q{a * b}(1.BigInt, iota(n - k + 1, n + 1));   enum combination = (in uint n, in uint k) pure => n.permutation(k) / reduce!q{a * b}(1.BigInt, iota(1, k + 1));   enu...
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#C.2B.2B
C++
#include <charconv> // std::from_chars #include <fstream> // file_to_string, string_to_file #include <functional> // std::invoke #include <iomanip> // std::setw #include <ios> // std::left #include <iostream> #include <map> // keywords #include <sstream> #include <string> #includ...
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#BBC_BASIC
BBC BASIC
PRINT @cmd$
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Blue
Blue
  global _start   : syscall ( num:eax -- result:eax | rcx ) syscall ;   : exit ( status:edi -- noret ) 60 syscall ; : bye ( -- noret ) 0 exit ; : die ( err:eax -- noret ) neg exit ;   : unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ; : ordie ( result -- ) unwrap drop ;   1 const stdout   : write ( buf:esi len:e...
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#BQN
BQN
•Show •args
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#AmigaE
AmigaE
/* multiline comment are like C ... */ -> this is a end of line comment
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#AntLang
AntLang
2 + 2 /This is a comment
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#ObjectIcon
ObjectIcon
# -*- ObjectIcon -*- # # The Rosetta Code virtual machine in Object Icon. # # See https://rosettacode.org/wiki/Compiler/virtual_machine_interpreter #   import io   procedure main(args) local f_inp, f_out local vm   if 3 <= *args then { write("Usage: ", &progname, " [INPUT_FILE [OUTPUT_FILE]]") exit(1) }...
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#Nim
Nim
import os, re, streams, strformat, strutils, tables, std/decls   type   # AST node types. NodeKind = enum nIdentifier = "Identifier" nString = "String" nInteger = "Integer" nSequence = "Sequence" nIf = "If" nPrtc = "Prtc" nPr...
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ruby
Ruby
class Array def radix_sort(base=10) # negative value is inapplicable. ary = dup rounds = (Math.log(ary.max)/Math.log(base)).ceil rounds.times do |i| buckets = Array.new(base){[]} base_i = base**i ary.each do |n| digit = (n/base_i) % base buckets[digit] << n en...
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
list = {"abcd", "123456789", "abcdef", "1234567"}; Reverse@SortBy[list, StringLength] // TableForm
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Nim
Nim
import strformat, unicode   const S1 = "marche" S2 = "marché"   echo &"“{S2}”, byte length = {S2.len}, code points: {S2.toRunes.len}" echo &"“{S1}”, byte length = {S1.len}, code points: {S1.toRunes.len}"
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read in...
#RATFOR
RATFOR
###################################################################### # # The Rosetta Code parser in Ratfor 77. # # # Ratfor 77 is a preprocessor for FORTRAN 77; therefore we do not have # recursive calls available. For printing the flattened tree, I use an # ordinary non-recursive implementation of the tree traversa...
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#E
E
def gridWidth := 3 def gridHeight := 3 def X := 0..!gridWidth def Y := 0..!gridHeight   def makeFlexList := <elib:tables.makeFlexList> def makeGrid() { def storage := makeFlexList.fromType(<type:java.lang.Boolean>, gridWidth * gridHeight) storage.setSize(gridWidth * gridHeight)   def grid { to __printOn(out) ...
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Rust
Rust
// Defines a generic struct where x and y can be of any type T struct Point<T> { x: T, y: T, } fn main() { let p = Point { x: 1.0, y: 2.5 }; // p is of type Point<f64> println!("{}, {}", p.x, p.y); }
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Scala
Scala
case class Point(x: Int = 0, y: Int = 0)   val p = Point(1, 2) println(p.y) //=> 2
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Batch_File
Batch File
  IF [NOT] ERRORLEVEL number command IF [NOT] string1==string2 command IF [NOT] EXIST filename command IF CMDEXTVERSION number command IF DEFINED variable command IF [/I] string1 compare-op string2 command where compare-op is: EQU - equal NEQ - not e...
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Racket
Racket
#lang racket (require (only-in srfi/13 [string-reverse gnirts]))   ;; returns a string with the "comma"s inserted every step characters from the RIGHT of n. ;; because of the right handedness of this, there is a lot of reversal going on (define ((insert-commas comma step) n) (define px (pregexp (format ".{1,~a}" step...
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Raku
Raku
for ('pi=3.14159265358979323846264338327950288419716939937510582097494459231', {:6at, :5by, :ins(' ')}), ('The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', {:ins<.>}), '-in Aus$+1411.8millions', '===US$0017440 millions=== (in 2000 dollars)', '123.e8000 is pretty big.', 'The land...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Delphi
Delphi
  program Compare_a_list_of_strings;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type // generic alias for use helper. The "TArray<string>" will be work too TListString = TArray<string>;   TListStringHelper = record helper for TListString function AllEqual: boolean; function AllLessThan: boolean; ...
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Astro
Astro
fun quibble(s): let result = s.join(' and ').replace(|| and ||, ", ", length(s) - 1) return "{ $result }"   let s = [ [] ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] ]   for i in s: print(quibble i)
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#AutoHotkey
AutoHotkey
MsgBox % quibble([]) MsgBox % quibble(["ABC"]) MsgBox % quibble(["ABC", "DEF"]) MsgBox % quibble(["ABC", "DEF", "G", "H"])   quibble(d) { s:="" for i, e in d { if (i<d.MaxIndex()-1) s:= s . e . ", " else if (i=d.MaxIndex()-1) s:= s . e . " and " else s:= s . e } return "{" . s . "}" }
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#BASIC256
BASIC256
arraybase 0 print "Enter n comb m. " input integer "n: ", n input integer "m: ", m outstr$ = "" dim names$(m)   for i = 0 to m - 1 print "Name for item "; i; ": "; input string names$[i] next i call iterate (outstr$, 0, m-1, n-1, names$) end   subroutine iterate(curr$, start, stp, depth, names$) for i = start to...
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#BBC_BASIC
BBC BASIC
DIM list$(2), chosen%(2) list$() = "iced", "jam", "plain" PRINT "Choices of 2 from 3:" choices% = FNchoose(0, 2, 0, 3, chosen%(), list$()) PRINT "Total choices = " ; choices%   PRINT '"Choices of 3 from 10:" choices% = FNchoose(0, 3, 0, 10, chosen%(), nul$()) PRINT "Total...
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at P...
#EchoLisp
EchoLisp
  ;; rename native functions according to task (define-syntax-rule (Cnk n k) (Cnp n k)) (define-syntax-rule (Ank n k) (Anp n k))     (Cnk 10 1) → 10 (lib 'bigint) ;; no floating point needed : use large integers   (Cnk 100 10) → 17310309456440 (Cnk 1000 42) → 297242911333923795640059429176065863139989673213...
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at P...
#Elixir
Elixir
defmodule Combinations_permutations do def perm(n, k), do: product(n - k + 1 .. n)   def comb(n, k), do: div( perm(n, k), product(1 .. k) )   defp product(a..b) when a>b, do: 1 defp product(list), do: Enum.reduce(list, 1, fn n, acc -> n * acc end)   def test do IO.puts "\nA sample of permutations from 1 t...
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#COBOL
COBOL
>>SOURCE FORMAT IS FREE *> this code is dedicated to the public domain *> (GnuCOBOL) 2.3-dev.0 identification division. program-id. lexer. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select input-file assign using input-name st...
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Bracmat
Bracmat
whl'(arg$:?a&out$(str$("next arg=" !a)))
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#C
C
#include <stdlib.h> #include <stdio.h>   int main(int argc, char* argv[]) { int i; (void) printf("This program is named %s.\n", argv[0]); for (i = 1; i < argc; ++i) (void) printf("the argument #%d is %s\n", i, argv[i]); return EXIT_SUCCESS; }
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Apex
Apex
  System.debug ('I will execute'); // This comment is ignored. /* I am a large comment, completely ignored as well. */  
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#APL
APL
⍝ This is a comment
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#Perl
Perl
#!/usr/bin/perl   # http://www.rosettacode.org/wiki/Compiler/virtual_machine_interpreter use strict; # vm.pl - run rosetta code use warnings; use integer;   my ($binary, $pc, @stack, @data) = ('', 0);   <> =~ /Strings: (\d+)/ or die "bad header"; my @strings = map <> =~ tr/\n""//dr =~ s/\\(.)/$1 eq 'n' ? "\n" : $1/ger,...
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#Perl
Perl
#!/usr/bin/perl   use strict; # gen.pl - flatAST to stack machine code use warnings; # http://www.rosettacode.org/wiki/Compiler/code_generator   my $stringcount = my $namecount = my $pairsym = my $pc = 0; my (%strings, %names); my %opnames = qw( Less lt LessEqual le Multiply mul Subtract sub Divide div GreaterEqual...
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Tcl
Tcl
############################################################################### # measure and plot times package require Tk package require struct::list namespace path ::tcl::mathfunc   proc create_log10_plot {title xlabel ylabel xs ys labels shapes colours} { set w [toplevel .[clock clicks]] wm title $w $title...
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Pascal
Pascal
program compareLengthOfStrings(output);   const specimenA = 'RosettaCode'; specimenB = 'Pascal'; specimenC = 'Foobar'; specimenD = 'Pascalish';   type specimen = (A, B, C, D); specimens = set of specimen value [];   const specimenMinimum = A; specimenMaximum = D;   var { the explicit range min..max serves as a...
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read in...
#Scala
Scala
  package xyz.hyperreal.rosettacodeCompiler   import scala.io.Source   object SyntaxAnalyzer {   val symbols = Map[String, (PrefixOperator, InfixOperator)]( "Op_or" -> (null, InfixOperator(10, LeftAssoc, BranchNode("Or", _, _))), "Op_and" -> (null, InfixOperator(20, LeftAssoc, Branc...
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#EasyLang
EasyLang
n = 70 n += 1 subr init for r = 1 to n - 1 for c = 1 to n - 1 i = r * n + c if randomf < 0.3 f[i] = 1 . . . . f = 100 / (n - 1) subr show clear for r = 1 to n - 1 for c = 1 to n - 1 if f[r * n + c] = 1 move (c - 1) * f (r - 1) * f rect f * 0.9 f * 0.9 ...
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Scheme
Scheme
(define-record-type point (make-point x y) point? (x point-x) (y point-y))
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Seed7
Seed7
const type: Point is new struct var integer: x is 0; var integer: y is 0; end struct;
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#BBC_BASIC
BBC BASIC
REM Single-line IF ... THEN ... ELSE (ELSE clause is optional): IF condition% THEN statements ELSE statements   REM Multi-line IF ... ENDIF (ELSE clause is optional): IF condition% THEN statements ELSE statements ENDIF   REM CASE ... ENDCASE (OTHERWISE clause is...
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#REXX
REXX
/*REXX program adds commas (or other chars) to a string or a number within a string.*/ @. = @.1= "pi=3.14159265358979323846264338327950288419716939937510582097494459231" @.2= "The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." @.3= "-in Aus$+1411.8millions" @.4= "===US$0017440 millions=== (in 2000...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Dyalect
Dyalect
func isSorted(xs) { var prev for x in xs { if prev && !(x > prev) { return false } prev = x } true }   func isEqual(xs) { var prev for x in xs { if prev && x != prev { return false } prev = x } true }
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Elena
Elena
import system'collections; import system'routines; import extensions;   extension helper { isEqual() = nil == self.seekEach(self.FirstMember, (n,m => m.equal:n.Inverted ));   isAscending() { var former := self.enumerator(); var later := self.enumerator();   later.next();   ...
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#AWK
AWK
function quibble(a, n, i, s) { for (i = 1; i < n - 1; i++) s = s a[i] ", " i = n - 1; if (i > 0) s = s a[i] " and " if (n > 0) s = s a[n] return "{" s "}" }   BEGIN { print quibble(a, 0) n = split("ABC", b); print quibble(b, n) n = split("ABC DEF", c); print quibble(c, n) n = split("ABC DEF G H", d); print q...
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Bracmat
Bracmat
( ( choices = n things thing result .  !arg:(?n.?things) & ( !n:0&1 | 0:?result & (  !things  :  ? ( %?`thing ?:?things &  !thing*choices$(!n+-1.!things)+!result  : ?result & ~ )...
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#C
C
  #include <stdio.h>   const char *donuts[] = {"iced", "jam", "plain", "something completely different"}; int pos[] = {0, 0, 0, 0};   void printDonuts(int k) { for (size_t i = 1; i < k + 1; i += 1) // offset: i:1..N, N=k+1 printf("%s\t", donuts[pos[i]]); // str:0..N-1 printf("\n"); }...
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at P...
#Erlang
Erlang
  -module(combinations_permutations).   -export([test/0]).   perm(N, K) -> product(lists:seq(N - K + 1, N)).   comb(N, K) -> perm(N, K) div product(lists:seq(1, K)).   product(List) -> lists:foldl(fun(N, Acc) -> N * Acc end, 1, List).   test() -> io:format("\nA sample of permutations from 1 to 12:\n"), ...
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#Common_Lisp
Common Lisp
(defpackage #:lexical-analyzer (:use #:cl #:sb-gray) (:export #:main))   (in-package #:lexical-analyzer)   (defconstant +lex-symbols-package+ (or (find-package :lex-symbols) (make-package :lex-symbols)))   (defclass counting-character-input-stream (fundamental-character-input-...
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#C.23
C#
using System;   namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#C.2B.2B
C++
#include <iostream>   int main(int argc, char* argv[]) { std::cout << "This program is named " << argv[0] << std::endl; std::cout << "There are " << argc-1 << " arguments given." << std::endl; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << std::endl;   return 0; }
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#AppleScript
AppleScript
  --This is a single line comment   display dialog "ok" --it can go at the end of a line   # Hash style comments are also supported   (* This is a multi line comment*)   (* This is a comment. --comments can be nested (* Nested block comment *) *)  
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Arendelle
Arendelle
  /* ARM assembly Raspberry PI comment one line */ /* comment line 1 comment line 2 */   mov r0,#0 @ this comment on end of line mov r1,#0 // authorized comment    
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#Phix
Phix
-- -- demo\rosetta\Compiler\vm.exw -- ============================ -- -- Since we have generated executable machine code, the virtual machine, such as it is, is just -- the higher level implementations of printc/i/s, see setbuiltins() in cgen.e -- Otherwise the only difference between this and cgen.exw is call(code...
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#Phix
Phix
-- -- demo\rosetta\Compiler\cgen.e -- ============================ -- -- The reusable part of cgen.exw -- without js -- (machine code!) include parse.e global sequence vars = {}, strings = {}, stringptrs = {} global integer chain = 0 global sequence code = {} function var_idx(sequenc...
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Wren
Wren
import "random" for Random import "/sort" for Sort import "/fmt" for Fmt   var rand = Random.new()   var onesSeq = Fn.new { |n| List.filled(n, 1) }   var shuffledSeq = Fn.new { |n| var seq = List.filled(n, 0) for (i in 0...n) seq[i] = 1 + rand.int(10 * n) return seq }   var ascendingSeq = Fn.new { |n| v...
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Compare_length_of_two_strings use warnings;   for ( 'shorter thelonger', 'abcd 123456789 abcdef 1234567' ) { print "\nfor strings => $_\n"; printf "length %d: %s\n", length(), $_ for sort { length $b <=> length $a } split; }
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Phix
Phix
with javascript_semantics sequence list = {"abcd","123456789","abcdef","1234567"}, lens = apply(list,length), tags = reverse(custom_sort(lens,tagset(length(lens)))) papply(true,printf,{1,{"%s (length %d)\n"},columnize({extract(list,tags),extract(lens,tags)})})
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read in...
#Scheme
Scheme
  (import (scheme base) (scheme process-context) (scheme write))   (define *names* (list (cons 'Op_add 'Add) (cons 'Op_subtract 'Subtract) (cons 'Op_multiply 'Multiply) (cons 'Op_divide 'Divide) (cons 'Op_mod 'Mod) ...
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#eC
eC
  import "ecere"   define seed = 12345; define popInit = 1000; define width = 100; define height = 100; define cellWidth = 4; define cellHeight = 4;   Array<byte> grid { size = width * height }; Array<byte> newState { size = width * height };   class GameOfLife : Window { caption = $"Conway's Game of Life"; backg...
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Shen
Shen
(datatype point X : number; Y : number; ==================== [point X Y] : point;)
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Sidef
Sidef
struct Point {x, y}; var point = Point(1, 2); say point.y; #=> 2
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#beeswax
beeswax
  ' lstack top value == 0 ? skip next instruction : don’t skip next instruction. " lstack top value > 0 ? skip next instruction : don’t skip next instruction. K lstack top value == 2nd value ? skip next instruction : don’t skip next instruction. L lstack top value > 2nd value ? skip next instructi...
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Scala
Scala
import java.io.File import java.util.Scanner import java.util.regex.Pattern   object CommatizingNumbers extends App {   def commatize(s: String): Unit = commatize(s, 0, 3, ",")   def commatize(s: String, start: Int, step: Int, ins: String): Unit = { if (start >= 0 && start <= s.length && step >= 1 && step <= s....
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Swift
Swift
import Foundation   extension String { private static let commaReg = try! NSRegularExpression(pattern: "(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)")   public func commatize(start: Int = 0, period: Int = 3, separator: String = ",") -> String { guard separator != "" else { return self }   let sep = Arra...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Elixir
Elixir
defmodule RC do def compare_strings(strings) do {length(Enum.uniq(strings))<=1, strict_ascending(strings)} end   defp strict_ascending(strings) when length(strings) <= 1, do: true defp strict_ascending([first, second | _]) when first >= second, do: false defp strict_ascending([_, second | rest]), do: stri...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Erlang
Erlang
  -module(compare_strings).   -export([all_equal/1,all_incr/1]).   all_equal(Strings) -> all_fulfill(fun(S1,S2) -> S1 == S2 end,Strings).   all_incr(Strings) -> all_fulfill(fun(S1,S2) -> S1 < S2 end,Strings).   all_fulfill(Fun,Strings) -> lists:all(fun(X) -> X end,lists:zipwith(Fun, lists:droplast(Strings), tl(Strin...
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion ::THE MAIN THING... echo. set inp=[] call :quibble set inp=["ABC"] call :quibble set inp=["ABC","DEF"] call :quibble set inp=["ABC","DEF","G","H"] call :quibble echo. pause exit /b ::/THE MAIN THING... ::THE FUNCTION :quibble set cont=0 set proc=%inp:[=% set proc=%proc:]=%   ...
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#C.23
C#
  using System; using System.Collections.Generic; using System.Linq;   public static class MultiCombinations { private static void Main() { var set = new List<string> { "iced", "jam", "plain" }; var combinations = GenerateCombinations(set, 2);   foreach (var combination in combinations) ...
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at P...
#Factor
Factor
USING: math.combinatorics prettyprint ;   1000 10 nCk .  ! 263409560461970212832400 1000 10 nPk .  ! 955860613004397508326213120000
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at P...
#FreeBASIC
FreeBASIC
Function PermBig(x As Long, y As Long) As ULongint Dim As Long i Dim As Longint z = 1 For i = x - y + 1 To x z = z * i Next i Return (z) End Function   Function FactBig(x As Long) As ULongint Dim As Long i Dim As Longint z = 1 For i = 2 To x z = z * i Next i Retur...
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#Elixir
Elixir
#!/bin/env elixir # -*- elixir -*-   defmodule Lex do   def main args do {inpf_name, outf_name, exit_status} = case args do [] -> {"-", "-", 0} [name] -> {name, "-", 0} [name1, name2] -> {name1, name2, 0} [name1, name2 | _] -> {name1, name2, usage_error()} end   {in...