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 programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   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 of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#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..str.high : return   # Extract first number (if any). let (lowBound, highBound) = str.findBounds(r, startIndex) if lowBound < 0: return let match = str[lowBound..highBound] let splits = match.split('.')   # Process integer part. ip = splits[0] if ip.len > period: var inserted = 0 for i in countup(ip.high mod period + 1, ip.high, period): ip.insert(sep, i + inserted) inserted += sep.len   # Process decimal part. if '.' in match: dp = splits[1] if dp.len > period: for i in countdown(dp.high div period * period, period, period): dp.insert(sep, i) ip &= '.' & dp   # Replace the number by its "commatized" version. result[lowBound..highBound] = ip     #———————————————————————————————————————————————————————————————————————————————————————————————————   const Tests = [ "123456789.123456789", ".123456789", "57256.1D-4", "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "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 of the earth is 57268900(29% of the surface) square miles.", "Ain't no numbers in this here words, nohow, no way, Jose.", "James was never known as 0000000007", "Arthur Eddington wrote: I believe there are " & "15747724136275002577605653961181555468044717914527116709366231425076185631031296" & " protons in the universe.", " $-140000±100 millions.", "6/9/1946 was a good year for some."]     echo Tests[0].commatize(period = 2, sep = "*") echo Tests[1].commatize(period = 3, sep = "-") echo Tests[2].commatize(period = 4, sep = "__") echo Tests[3].commatize(period = 5, sep = " ") echo Tests[4].commatize(sep = ".")   for n in 5..Tests.high: echo Tests[n].commatize()
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 programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   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 of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#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 of the earth is 57268900(29% of the surface) square miles.'], ['Ain\'t no numbers in this here words, nohow, no way, Jose.'], ['James was never known as 0000000007'], ['Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.'], [' $-140000±100 millions.'], ['5/9/1946 was a good year for some.'] );   for $i (@input) { $old = @$i[0]; $new = commatize(@$i); printf("%s\n%s\n\n", $old, $new) if $old ne $new; }   sub commatize { my($str,$sep,$by) = @_; $sep = ',' unless $sep; $by = 3 unless $by;   $str =~ s/ # matching rules: (?<![eE\/]) # not following these characters ([1-9]\d{$by,}) # leading non-zero digit, minimum number of digits required /c_ins($1,$by,$sep)/ex; # substitute matched text with subroutine output return $str; }   sub c_ins { my($s,$by,$sep) = @_; ($c = reverse $s) =~ s/(.{$by})/$1$sep/g; $c =~ s/$sep$//; return reverse $c; }
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 the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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). 01 results. 05 filler pic 9(1). 88 equal-strings value 1 when set to false is 0. 05 filler pic 9(1). 88 ordered-strings value 1 when set to false is 0.   procedure division. main. move "AA BB CC" to the-list perform check-list move "AA AA AA" to the-list perform check-list move "AA CC BB" to the-list perform check-list move "AA ACBBB CC" to the-list perform check-list move "AA" to the-list perform check-list stop run . check-list. display "list:" set equal-strings to true set ordered-strings to true perform varying i from 1 by 1 until i > MAX-ITEMS if list-item(i) <> spaces display function trim(list-item(i)), " " no advancing if i < MAX-ITEMS and list-item(i + 1) <> spaces if list-item(i + 1) <> list-item(i) set equal-strings to false end-if if list-item(i + 1) <= list-item(i) set ordered-strings to false end-if end-if end-if end-perform display " " if equal-strings display "... is lexically equal" else display "... is not lexically equal" end-if if ordered-strings display "... is in strict ascending order" else display "... is not in strict ascending order" end-if display " " .
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. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#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 ) ; begin string(256) list; integer wordCount, wordNumber, listPos; logical inWord;    % returns true if ch is an upper-case letter, false otherwise  %  % assumes the letters are consecutive in the character set  %  % (as in ascii) would not be correct if the character set was %  % ebcdic (as in the original implementations of Algol W)  % logical procedure isUpper ( string(1) value ch ) ; ch >= "A" and ch <= "Z" ;    % adds a character to the result  % procedure addChar( string(1) value ch ) ; begin list( listPos // 1 ) := ch; listPos := listPos + 1; end addChar ;    % adds a string to the result  % procedure addString( string(256) value str  ; integer value len ) ; for strPos := 0 until len - 1 do addChar( str( strPos // 1 ) );    % count the number of words  %   wordCount := 0; inWord  := false; for charPos := 0 until 255 do begin if isUpper( words( charPos // 1 ) ) then begin  % not an upper-case letter, possibly a word has been ended  % inWord := false end else begin  % not a delimitor, possibly the start of a word  % if not inWord then begin  % we are starting a new word  % wordCount := wordCount + 1; inWord  := true end if_not_inWord end end for_charPos;    % format the result  %   list  := ""; listPos  := 0; inWord  := false; wordNumber := 0;   addChar( "{" );   for charPos := 0 until 255 do begin if not isUpper( words( charPos // 1 ) ) then begin  % not an upper-case letter, possibly a word has been ended  % inWord := false end else begin  % not a delimitor, possibly the start of a word  % if not inWord then begin  % we are starting a new word  % wordNumber := wordNumber + 1; inWord  := true; if wordNumber > 1 then begin  % second or subsequent word - need a separator  % if wordNumber = wordCount then addString( " and ", 5 ) % final word % else addString( ", ", 2 ) % non-final word % end end;  % add the character to the result  % addChar( words( charPos // 1 ) ) end end for_charPos ;   addChar( "}" );   list end toList ;      % procedure to test the toList procedure  % procedure testToList ( string(256) value words ) ; begin string(256) list; list := toList( words ); write( s_w := 0 , words( 0 // 32 ) , ": " , list( 0 // 32 ) ) end testToList ;    % test the toList procedure  % testToList( "" ); testToList( "ABC" ); testToList( "ABC DEF" ); testToList( "ABC DEF G H" );   end.
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. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#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   -- TEST ----------------------------------------------------------------------- on run script braces on |λ|(x) "{" & x & "}" end |λ| end script   unlines(map(compose({braces, quibble}), ¬ append({{}, {"ABC"}, {"ABC", "DEF"}, {"ABC", "DEF", "G", "H"}}, ¬ map(|words|, ¬ {"One two three four", "Me myself I", "Jack Jill", "Loner"})))) end run     -- GENERIC FUNCTIONS ----------------------------------------------------------   -- A list of functions applied to a list of arguments -- (<*> | ap) :: [(a -> b)] -> [a] -> [b] on ap(fs, xs) set {intFs, intXs} to {length of fs, length of xs} set lst to {} repeat with i from 1 to intFs tell mReturn(item i of fs) repeat with j from 1 to intXs set end of lst to |λ|(contents of (item j of xs)) end repeat end tell end repeat return lst end ap   -- (++) :: [a] -> [a] -> [a] on append(xs, ys) xs & ys end append   -- compose :: [(a -> a)] -> (a -> a) on compose(fs) script on |λ|(x) script on |λ|(a, f) mReturn(f)'s |λ|(a) end |λ| end script   foldr(result, x, fs) end |λ| end script end compose   -- concat :: [[a]] -> [a] | [String] -> String on concat(xs) script append on |λ|(a, b) a & b end |λ| end script   if length of xs > 0 and class of (item 1 of xs) is string then set unit to "" else set unit to {} end if foldl(append, unit, xs) end concat   -- curry :: (Script|Handler) -> Script on curry(f) script on |λ|(a) script on |λ|(b) |λ|(a, b) of mReturn(f) end |λ| end script end |λ| end script end curry   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- foldr :: (a -> b -> a) -> a -> [b] -> a on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldr   -- head :: [a] -> a on head(xs) if length of xs > 0 then item 1 of xs else missing value end if end head   -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- |reverse| :: [a] -> [a] on |reverse|(xs) if class of xs is text then (reverse of characters of xs) as text else reverse of xs end if end |reverse|   -- tail :: [a] -> [a] on tail(xs) if length of xs > 1 then items 2 thru -1 of xs else {} end if end tail   -- unlines :: [String] -> String on unlines(xs) intercalate(linefeed, xs) end unlines   -- words :: String -> [String] on |words|(s) words of s end |words|
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 {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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:=[]) return result } ;=========================================================== CombinationRepetitionUtil(arr, k, Delim, chosen, result , index:=1, start:=1){ line := [], i:=0, res := "" if (index = k+1){ while (++i <= k) res .= arr[chosen[i]] Delim, line.push(arr[chosen[i]]) return result.Push(Trim(res, Delim)) } i:=start while (i <= arr.count()) chosen[Index]:=i, CombinationRepetitionUtil(arr, k, Delim, chosen, result, index+1, i++) } ;===========================================================
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 Permutation. 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) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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_plus(self) - lgamma_plus(self - k) - lgamma_plus(k)) end   private def lgamma_plus(n) lgamma(n+1) #lgamma is the natural log of gamma end   end   p 12.permutation(9) #=> 79833600 p 12.big_permutation(9) #=> 79833600.00000021 p 60.combination(53) #=> 386206920 p 145.big_permutation(133) #=> 1.6801459655817956e+243 p 900.big_combination(450) #=> 2.247471882064647e+269 p 1000.big_combination(969) #=> 7.602322407770517e+58 p 15000.big_permutation(73) #=> 6.004137561717704e+304 #That's about the maximum of Float: p 15000.big_permutation(74) #=> Infinity #Fixnum has no maximum: p 15000.permutation(74) #=> 896237613852967826239917238565433149353074416025197784301593335243699358040738127950872384197159884905490054194835376498534786047382445592358843238688903318467070575184552953997615178973027752714539513893159815472948987921587671399790410958903188816684444202526779550201576117111844818124800000000000000000000    
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 also used to refer to the first stage of a lexer). Task[edit] Create a lexical analyzer for the simple programming language specified below. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a lexer module/library/class, it would be great if two versions of the solution are provided: One without the lexer module, and one with. Input Specification The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens: Operators Name Common name Character sequence Op_multiply multiply * Op_divide divide / Op_mod mod % Op_add plus + Op_subtract minus - Op_negate unary minus - Op_less less than < Op_lessequal less than or equal <= Op_greater greater than > Op_greaterequal greater than or equal >= Op_equal equal == Op_notequal not equal != Op_not unary not ! Op_assign assignment = Op_and logical and && Op_or logical or ¦¦ The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task. Symbols Name Common name Character LeftParen left parenthesis ( RightParen right parenthesis ) LeftBrace left brace { RightBrace right brace } Semicolon semi-colon ; Comma comma , Keywords Name Character sequence Keyword_if if Keyword_else else Keyword_while while Keyword_print print Keyword_putc putc Identifiers and literals These differ from the the previous tokens, in that each occurrence of them has a value associated with it. Name Common name Format description Format regex Value Identifier identifier one or more letter/number/underscore characters, but not starting with a number [_a-zA-Z][_a-zA-Z0-9]* as is Integer integer literal one or more digits [0-9]+ as is, interpreted as a number Integer char literal exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes '([^'\n]|\\n|\\\\)' the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n' String string literal zero or more characters (anything except newline or double quote), enclosed by double quotes "[^"\n]*" the characters without the double quotes and with escape sequences converted For char and string literals, the \n escape sequence is supported to represent a new-line character. For char and string literals, to represent a backslash, use \\. No other special sequences are supported. This means that: Char literals cannot represent a single quote character (value 39). String literals cannot represent strings containing double quote characters. Zero-width tokens Name Location End_of_input when the end of the input stream is reached White space Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below. "Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =). Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge. This means: keywords, identifiers, and integer literals. e.g. ifprint is recognized as an identifier, instead of the keywords if and print. e.g. 42fred is invalid, and neither recognized as a number nor an identifier. Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value). e.g. & & is invalid, and not interpreted as the && operator. For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions: if ( p /* meaning n is prime */ ) { print ( n , " " ) ; count = count + 1 ; /* number of primes found so far */ } if(p){print(n," ");count=count+1;} Complete list of token names 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_notequal Op_assign Op_and Op_or Keyword_if Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen LeftBrace RightBrace Semicolon Comma Identifier Integer String Output Format The program output should be a sequence of lines, each consisting of the following whitespace-separated fields: the line number where the token starts the column number where the token starts the token name the token value (only for Identifier, Integer, and String tokens) the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement. This task is intended to be used as part of a pipeline, with the other compiler tasks - for example: lex < hello.t | parse | gen | vm Or possibly: lex hello.t lex.out parse lex.out parse.out gen parse.out gen.out vm gen.out This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs. Diagnostics The following error conditions should be caught: Error Example Empty character constant '' Unknown escape sequence. \r Multi-character constant. 'xx' End-of-file in comment. Closing comment characters not found. End-of-file while scanning string literal. Closing string character not found. End-of-line while scanning string literal. Closing string character not found before end-of-line. Unrecognized character. | Invalid number. Starts like a number, but ends in non-numeric characters. 123abc Test Cases Input Output Test Case 1: /* Hello world */ print("Hello, World!\n"); 4 1 Keyword_print 4 6 LeftParen 4 7 String "Hello, World!\n" 4 24 RightParen 4 25 Semicolon 5 1 End_of_input Test Case 2: /* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, "\n"); 4 1 Identifier phoenix_number 4 16 Op_assign 4 18 Integer 142857 4 24 Semicolon 5 1 Keyword_print 5 6 LeftParen 5 7 Identifier phoenix_number 5 21 Comma 5 23 String "\n" 5 27 RightParen 5 28 Semicolon 6 1 End_of_input Test Case 3: /* All lexical tokens - not syntactically correct, but that will have to wait until syntax analysis */ /* Print */ print /* Sub */ - /* Putc */ putc /* Lss */ < /* If */ if /* Gtr */ > /* Else */ else /* Leq */ <= /* While */ while /* Geq */ >= /* Lbrace */ { /* Eq */ == /* Rbrace */ } /* Neq */ != /* Lparen */ ( /* And */ && /* Rparen */ ) /* Or */ || /* Uminus */ - /* Semi */ ; /* Not */ ! /* Comma */ , /* Mul */ * /* Assign */ = /* Div */ / /* Integer */ 42 /* Mod */ % /* String */ "String literal" /* Add */ + /* Ident */ variable_name /* character literal */ '\n' /* character literal */ '\\' /* character literal */ ' ' 5 16 Keyword_print 5 40 Op_subtract 6 16 Keyword_putc 6 40 Op_less 7 16 Keyword_if 7 40 Op_greater 8 16 Keyword_else 8 40 Op_lessequal 9 16 Keyword_while 9 40 Op_greaterequal 10 16 LeftBrace 10 40 Op_equal 11 16 RightBrace 11 40 Op_notequal 12 16 LeftParen 12 40 Op_and 13 16 RightParen 13 40 Op_or 14 16 Op_subtract 14 40 Semicolon 15 16 Op_not 15 40 Comma 16 16 Op_multiply 16 40 Op_assign 17 16 Op_divide 17 40 Integer 42 18 16 Op_mod 18 40 String "String literal" 19 16 Op_add 19 40 Identifier variable_name 20 26 Integer 10 21 26 Integer 92 22 26 Integer 32 23 1 End_of_input Test Case 4: /*** test printing, embedded \n and comments with lots of '*' ***/ print(42); print("\nHello World\nGood Bye\nok\n"); print("Print a slash n - \\n.\n"); 2 1 Keyword_print 2 6 LeftParen 2 7 Integer 42 2 9 RightParen 2 10 Semicolon 3 1 Keyword_print 3 6 LeftParen 3 7 String "\nHello World\nGood Bye\nok\n" 3 38 RightParen 3 39 Semicolon 4 1 Keyword_print 4 6 LeftParen 4 7 String "Print a slash n - \\n.\n" 4 33 RightParen 4 34 Semicolon 5 1 End_of_input Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Syntax Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#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_notequal, Op_assign, Op_and, Op_or, Keyword_if, Keyword_else, Keyword_while, Keyword_print, Keyword_putc, LeftParen, RightParen, LeftBrace, RightBrace, Semicolon, Comma, Identifier, Integer, String, None }   /// <summary> /// Storage class for tokens /// </summary> public class Token { public TokenType Type { get; set; } public int Line { get; set; } public int Position { get; set; } public string Value { get; set; } public override string ToString() { if (Type == TokenType.Integer || Type == TokenType.Identifier) { return String.Format("{0,-5} {1,-5} {2,-14} {3}", Line, Position, Type.ToString(), Value); } else if (Type == TokenType.String) { return String.Format("{0,-5} {1,-5} {2,-14} \"{3}\"", Line, Position, Type.ToString(), Value.Replace("\n", "\\n")); } return String.Format("{0,-5} {1,-5} {2,-14}", Line, Position, Type.ToString()); } }   /// <summary> /// C# Example of Lexical scanner for Rosetta Compiler /// </summary> public class LexicalScanner {   // character classes private const string _letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_"; private const string _numbers = "0123456789"; private const string _identifier = _letters + _numbers + "_"; private const string _whitespace = " \t\n\r";   // mappings from string keywords to token type private Dictionary<string, TokenType> _keywordTokenTypeMap = new Dictionary<string, TokenType>() { { "if", TokenType.Keyword_if }, { "else", TokenType.Keyword_else }, { "while", TokenType.Keyword_while }, { "print", TokenType.Keyword_print }, { "putc", TokenType.Keyword_putc } };   // mappings from simple operators to token type private Dictionary<string, TokenType> _operatorTokenTypeMap = new Dictionary<string, TokenType>() { { "+", TokenType.Op_add }, { "-", TokenType.Op_subtract }, { "*", TokenType.Op_multiply }, { "/", TokenType.Op_divide }, { "%", TokenType.Op_mod }, { "=", TokenType.Op_assign }, { "<", TokenType.Op_less }, { ">", TokenType.Op_greater }, { "!", TokenType.Op_not }, };   private List<string> _keywords; private string _operators = "+-*/%=<>!%";   private string _code; private List<Token> tokens = new List<Token>();   private int _line = 1; private int _position = 1;   public string CurrentCharacter { get { try { return _code.Substring(0, 1); } catch (ArgumentOutOfRangeException) { return ""; } } }   /// <summary> /// Lexical scanner initialiser /// </summary> /// <param name="code">Code to be tokenised</param> public LexicalScanner (string code) { _code = code; _keywords = _keywordTokenTypeMap.Keys.ToList(); }   /// <summary> /// Advance the cursor forward given number of characters /// </summary> /// <param name="characters">Number of characters to advance</param> private void advance(int characters=1) { try { // reset position when there is a newline if (CurrentCharacter == "\n") { _position = 0; _line++; }   _code = _code.Substring(characters, _code.Length - characters); _position += characters; } catch (ArgumentOutOfRangeException) { _code = ""; } }   /// <summary> /// Outputs error message to the console and exits /// </summary> /// <param name="message">Error message to display to user</param> /// <param name="line">Line error occurred on</param> /// <param name="position">Line column that the error occurred at</param> public void error(string message, int line, int position) { // output error to the console and exit Console.WriteLine(String.Format("{0} @ {1}:{2}", message, line, position)); Environment.Exit(1); }   /// <summary> /// Pattern matching using first & follow matching /// </summary> /// <param name="recogniseClass">String of characters that identifies the token type /// or the exact match the be made if exact:true</param> /// <param name="matchClass">String of characters to match against remaining target characters</param> /// <param name="tokenType">Type of token the match represents.</param> /// <param name="notNextClass">Optional class of characters that cannot follow the match</param> /// <param name="maxLen">Optional maximum length of token value</param> /// <param name="exact">Denotes whether recogniseClass represents an exact match or class match. /// Default: false</param> /// <param name="discard">Denotes whether the token is kept or discarded. Default: false</param> /// <param name="offset">Optiona line position offset to account for discarded tokens</param> /// <returns>Boolean indicating if a match was made </returns> public bool match(string recogniseClass, string matchClass, TokenType tokenType, string notNextClass=null, int maxLen=Int32.MaxValue, bool exact=false, bool discard=false, int offset=0) {   // if we've hit the end of the file, there's no more matching to be done if (CurrentCharacter == "") return false;   // store _current_ line and position so that our vectors point at the start // of each token int line = _line; int position = _position;   // special case exact tokens to avoid needing to worry about backtracking if (exact) { if (_code.StartsWith(recogniseClass)) { if (!discard) tokens.Add(new Token() { Type = tokenType, Value = recogniseClass, Line = line, Position = position - offset}); advance(recogniseClass.Length); return true; } return false; }   // first match - denotes the token type usually if (!recogniseClass.Contains(CurrentCharacter)) return false;   string tokenValue = CurrentCharacter; advance();   // follow match while we haven't exceeded maxLen and there are still characters // in the code stream while ((matchClass ?? "").Contains(CurrentCharacter) && tokenValue.Length <= maxLen && CurrentCharacter != "") { tokenValue += CurrentCharacter; advance(); }   // ensure that any incompatible characters are not next to the token // eg 42fred is invalid, and neither recognized as a number nor an identifier. // _letters would be the notNextClass if (notNextClass != null && notNextClass.Contains(CurrentCharacter)) error("Unrecognised character: " + CurrentCharacter, _line, _position);   // only add tokens to the stack that aren't marked as discard - dont want // things like open and close quotes/comments if (!discard) { Token token = new Token() { Type = tokenType, Value = tokenValue, Line = line, Position = position - offset }; tokens.Add(token); }   return true; }   /// <summary> /// Tokenise the input code /// </summary> /// <returns>List of Tokens</returns> public List<Token> scan() {   while (CurrentCharacter != "") { // match whitespace match(_whitespace, _whitespace, TokenType.None, discard: true);   // match integers match(_numbers, _numbers, TokenType.Integer, notNextClass:_letters);   // match identifiers and keywords if (match(_letters, _identifier, TokenType.Identifier)) { Token match = tokens.Last(); if (_keywords.Contains(match.Value)) match.Type = _keywordTokenTypeMap[match.Value]; }   // match string similarly to comments without allowing newlines // this token doesn't get discarded though if (match("\"", null, TokenType.String, discard:true)) { string value = ""; int position = _position; while (!match("\"", null, TokenType.String, discard:true)) { // not allowed newlines in strings if (CurrentCharacter == "\n") error("End-of-line while scanning string literal. Closing string character not found before end-of-line", _line, _position); // end of file reached before finding end of string if (CurrentCharacter == "") error("End-of-file while scanning string literal. Closing string character not found", _line, _position);   value += CurrentCharacter;   // deal with escape sequences - we only accept newline (\n) if (value.Length >= 2) { string lastCharacters = value.Substring(value.Length - 2, 2); if (lastCharacters[0] == '\\') { if (lastCharacters[1] != 'n') { error("Unknown escape sequence. ", _line, position); } value = value.Substring(0, value.Length - 2).ToString() + "\n"; } }   advance(); } tokens.Add(new Token() { Type = TokenType.String, Value = value, Line = _line, Position = position - 1}); }   // match string literals if (match("'", null, TokenType.Integer, discard:true)) { int value; int position = _position; value = CurrentCharacter.ToCharArray()[0]; advance();   // deal with empty literals '' if (value == '\'') error("Empty character literal", _line, _position);   // deal with escaped characters, only need to worry about \n and \\ // throw werror on any other if (value == '\\') { if (CurrentCharacter == "n") { value = '\n'; } else if (CurrentCharacter == "\\") { value = '\\'; } else { error("Unknown escape sequence. ", _line, _position - 1); } advance(); }   // if we haven't hit a closing ' here, there are two many characters // in the literal if (!match("'", null, TokenType.Integer, discard: true)) error("Multi-character constant", _line, _position);   tokens.Add(new Rosetta.Token() { Type = TokenType.Integer, Value = value.ToString(), Line = _line, Position = position - 1 }); }   // match comments by checking for starting token, then advancing // until closing token is matched if (match("/*", null, TokenType.None, exact: true, discard: true)) { while (!match("*/", null, TokenType.None, exact: true, discard: true)) { // reached the end of the file without closing comment! if (CurrentCharacter == "") error("End-of-file in comment. Closing comment characters not found.", _line, _position); advance(); } continue; }   // match complex operators match("<=", null, TokenType.Op_lessequal, exact: true); match(">=", null, TokenType.Op_greaterequal, exact: true); match("==", null, TokenType.Op_equal, exact: true); match("!=", null, TokenType.Op_notequal, exact: true); match("&&", null, TokenType.Op_and, exact: true); match("||", null, TokenType.Op_or, exact: true);   // match simple operators if (match(_operators, null, TokenType.None, maxLen:1)) { Token match = tokens.Last(); match.Type = _operatorTokenTypeMap[match.Value]; }   // brackets, braces and separators match("(", null, TokenType.LeftParen, exact: true); match(")", null, TokenType.RightParen, exact: true); match("{", null, TokenType.LeftBrace, exact: true); match("}", null, TokenType.RightBrace, exact: true); match(";", null, TokenType.Semicolon, exact: true); match(",", null, TokenType.Comma, exact: true);   }   // end of file token tokens.Add(new Rosetta.Token() { Type = TokenType.End_of_input, Line = _line, Position = _position });   return tokens; }   static void Main (string[] args) { StreamReader inputFile;   // if we passed in a filename, read code from that, else // read code from stdin if (args.Length > 0) { string path = args[0]; try { inputFile = new StreamReader(path); } catch (IOException) { inputFile = new StreamReader(Console.OpenStandardInput(8192)); } } else { inputFile = new StreamReader(Console.OpenStandardInput(8192)); }   string code = inputFile.ReadToEnd();   // strip windows line endings out code = code.Replace("\r", "");   LexicalScanner scanner = new LexicalScanner(code); List<Token> tokens = scanner.scan();   foreach(Token token in tokens) { Console.WriteLine(token.ToString()); } } } }  
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, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#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 = "sub" opMul = "mul" opDiv = "div" opMod = "mod" opLt = "lt" opgt = "gt" opLe = "le" opGe = "ge" opEq = "eq" opNe = "ne" opAnd = "and" opOr = "or" opNeg = "neg" opNot = "not" opPrtc = "prtc" opPrti = "prti" opPrts = "prts" opHalt = "halt" opInvalid = "invalid"   # Virtual machine description. VM = object stack: seq[Value] # Evaluation stack. memory: seq[byte] # Memory to store program. data: seq[Value] # Data storage. strings: seq[string] # String storage. pc: Address # Program counter.   # Exceptions. LoadingError = object of CatchableError RuntimeError = object of CatchableError     #################################################################################################### # Running program.   proc checkStackLength(vm: VM; minLength: int) {.inline.} = ## Check that evaluation stack contains at least "minLength" elements. if vm.stack.len < minLength: raise newException(RuntimeError, &"not enough operands on the stack (pc = {vm.pc}).")   #---------------------------------------------------------------------------------------------------   proc getOperand(vm: var VM): Value = ## Get a 32 bits operand.   type Union {.union.} = object value: Value bytes: BytesValue   if vm.pc + 4 >= vm.memory.len: raise newException(RuntimeError, &"out of memory (pc = {vm.pc}).")   var aux: Union let address = vm.pc + 1 for idx in 0..3: aux.bytes[idx] = vm.memory[address + idx] result = aux.value   #---------------------------------------------------------------------------------------------------   proc run(vm: var VM) = ## Run a program loaded in VM memory.   vm.pc = 0   while true:   if vm.pc notin 0..vm.memory.high: raise newException(RuntimeError, &"out of memory (pc = {vm.pc}).")   let opcode = OpCode(vm.memory[vm.pc]) case opcode   of opFetch, opStore: let index = vm.getOperand() if index notin 0..vm.data.high: raise newException(RuntimeError, &"wrong memory index (pc = {vm.pc}).") if opcode == opFetch: vm.stack.add(vm.data[index]) else: vm.checkStackLength(1) vm.data[index] = vm.stack.pop() inc vm.pc, 4   of opPush: let value = vm.getOperand() vm.stack.add(value) inc vm.pc, 4   of opJmp: let offset = vm.getOperand() inc vm.pc, offset   of opJz: let offset = vm.getOperand() vm.checkStackLength(1) let value = vm.stack.pop() inc vm.pc, if value == 0: offset else: 4   of opAdd..opOr: # Two operands instructions. vm.checkStackLength(2) let op2 = vm.stack.pop() let op1 = vm.stack.pop() case range[opAdd..opOr](opcode) of opAdd: vm.stack.add(op1 + op2) of opSub: vm.stack.add(op1 - op2) of opMul: vm.stack.add(op1 * op2) of opDiv: vm.stack.add(op1 div op2) of opMod: vm.stack.add(op1 mod op2) of opLt: vm.stack.add(Value(op1 < op2)) of opgt: vm.stack.add(Value(op1 > op2)) of opLe: vm.stack.add(Value(op1 <= op2)) of opGe: vm.stack.add(Value(op1 >= op2)) of opEq: vm.stack.add(Value(op1 == op2)) of opNe: vm.stack.add(Value(op1 != op2)) of opAnd: vm.stack.add(op1 and op2) of opOr: vm.stack.add(op1 or op2)   of opNeg..opPrts: # One operand instructions. vm.checkStackLength(1) let op = vm.stack.pop() case range[opNeg..opPrts](opcode) of opNeg: vm.stack.add(-op) of opNot: vm.stack.add(not op) of opPrtc: stdout.write(chr(op)) of opPrti: stdout.write(op) of opPrts: if op notin 0..vm.strings.high: raise newException(RuntimeError, &"wrong string index (pc = {vm.pc}).") stdout.write(vm.strings[op])   of opHalt: break   of opInvalid: discard # Not possible.   inc vm.pc     #################################################################################################### # Loading assembly file.   proc parseHeader(line: string): tuple[dataSize, stringCount: int] = ## Parse the header.   if not line.scanf("Datasize: $s$i $sStrings: $i", result.dataSize, result.stringCount): raise newException(LoadingError, "Wrong header in code.")   #---------------------------------------------------------------------------------------------------   import re   proc parseString(line: string; linenum: int): string = ## Parse a string.   if not line.startsWith('"'): raise newException(LoadingError, "Line $1: incorrect string.".format(linenum)) # Can't use "unescape" as it is confused by "\\n" and "\n". result = line.replacef(re"([^\\])(\\n)", "$1\n").replace(r"\\", r"\").replace("\"", "")   #---------------------------------------------------------------------------------------------------   proc parseValue(line: string; linenum: int; pos: var int; msg: string): int32 = ## Parse an int32 value.   var value: int   pos += line.skipWhitespace(pos) let parsed = line.parseInt(value, pos) if parsed == 0: raise newException(LoadingError, "Line $1: ".format(linenum) & msg) pos += parsed result = int32(value)   #---------------------------------------------------------------------------------------------------   proc parseOpcode(line: string; linenum: int; pos: var int): OpCode = ## Parse an opcode.   var opstring: string   pos += line.skipWhitespace(pos) let parsed = line.parseIdent(opstring, pos) if parsed == 0: raise newException(LoadingError, "Line $1: opcode expected".format(linenum)) pos += parsed   result = parseEnum[OpCode](opstring, opInvalid) if result == opInvalid: raise newException(LoadingError, "Line $1: invalid opcode encountered".format(linenum))   #---------------------------------------------------------------------------------------------------   proc parseMemoryIndex(line: string; linenum: int; pos: var int): int32 = ## Parse a memory index (int32 value between brackets).   var memIndex: int   pos += line.skipWhitespace(pos) let str = line.captureBetween('[', ']', pos) if str.parseInt(memIndex) == 0 or memIndex < 0: raise newException(LoadingError, "Line $1: invalid memory index".format(lineNum)) pos += str.len + 2 result = int32(memIndex)   #---------------------------------------------------------------------------------------------------   proc parseOffset(line: string; linenum: int; pos: var int): int32 = ## Parse an offset (int32 value between parentheses).   var offset: int   pos += line.skipWhitespace(pos) let str = line.captureBetween('(', ')', pos) if str.parseInt(offset) == 0: raise newException(LoadingError, "Line $1: invalid offset".format(linenum)) pos += str.len + 2 result = int32(offset)   #---------------------------------------------------------------------------------------------------   proc load(vm: var VM; code: string) = ## Load an assembly code into VM memory.   # Analyze header. let lines = code.splitlines() let (dataSize, stringCount) = parseHeader(lines[0]) vm.data.setLen(dataSize) vm.strings.setLen(stringCount)   # Load strings. for idx in 1..stringCount: vm.strings[idx - 1] = lines[idx].parseString(idx + 1)   # Load code. var pc: Address = 0 for idx in (stringCount + 1)..lines.high: var pos = 0 let line = lines[idx] if line.len == 0: continue   # Process address. let address = line.parseValue(idx + 1, pos, "address expected") if address != pc: raise newException(LoadingError, "Line $1: wrong address".format(idx + 1))   # Process opcode. let opcode = line.parseOpcode(idx + 1, pos) vm.memory.add(byte(opcode))   # Process operand. case opcode   of opFetch, opStore: # Find memory index. let memIndex = line.parseMemoryIndex(idx + 1, pos) vm.memory.add(cast[BytesValue](Value(memIndex))) inc pc, 5   of opJmp, opJz: # Find offset. let offset = line.parseOffset(idx + 1, pos) vm.memory.add(cast[BytesValue](Value(offset))) # Find and check branch address. let branchAddress = line.parseValue(idx + 1, pos, "branch address expected") if branchAddress != pc + offset + 1: raise newException(LoadingError, "Line $1: wrong branch address".format(idx + 1)) inc pc, 5   of opPush: # Find value. let value = line.parseValue(idx + 1, pos, "value expected") vm.memory.add(cast[BytesValue](Value(value))) inc pc, 5   else: inc pc   #———————————————————————————————————————————————————————————————————————————————————————————————————   let code = if paramCount() == 0: stdin.readAll() else: paramStr(1).readFile() var vm: VM   vm.load(code) vm.run()
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 Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#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, gadd, gle, gsub, glt gle, ggt, gge, geq, gne, gand, gor, gprtc, gprti, gprts, gif, gwhile, gAssign, gSeq, gstring, gidentifier, gint, gnone }   \\ Inventories are lists with keys, or keys/data (key must be unique) \\ there is one type more the Invetory Queue which get same keys. \\ But here not used. Inventory symb="Multiply":=gmul, "Divide":=gdiv, "Mod":=gmod, "Add":=gadd Append symb, "Negate":=gneg, "Not":=gnot,"Less":=glt,"Subtract":=gsub Append symb, "LessEqual":=gle, "Greater":=ggt, "GreaterEqual":=gge, "Sequence":=gSeq Append symb, "Equal":=geq, "NotEqual":=gne, "And":=gand, "Or":=gor, "While":=gwhile Append symb, "Prtc":=gprtc,"Prti":=gprti,"Prts":=gprts, "Assign":=gAssign, "If":=gif Append symb, "String":=gstring, "Identifier":=gidentifier, "Integer":=gint, ";", gnone   Inventory DataSet \\ We set string as key. key maybe an empty string, a string or a number. \\ so we want eash string to saved one time only. Inventory Strings   Const nl$=chr$(13)+chr$(10), Ansi=3 Def z$, lim, line$, newvar_ok, i=0 Document message$=nl$ Global pc \\ functions have own scope, so we make it global, for this module, and childs.   Dim lines$() s$=filter$(s$,chr$(9)) \\ exclude tabs Lines$()=piece$(s$,nl$) \\ break to lines lim=len(Lines$()) Flush ' empty stack (there is a current stack of values which we use here)   Load_Ast() If not stack.size=1 Then Flush : Error "Ast not loaded" AST=array \\ pop the array from stack Document Assembly$, Header$   \\ all lines of assembly goes to stack. Maybe not in right order. \\ Push statement push to top, Data statement push to bottom of stack   CodeGenerator(Ast) Data code$("halt") ' append to end of stack \\ So now we get all data (letters) from stack While not empty Assembly$=letter$+nl$ end while \\ So now we have to place them in order Sort Assembly$   \\ Let's make the header Header$=format$("Datasize: {0} Strings: {1}", Len(Dataset),Len(strings)) \\ we use an iterator object, str^ is the counter, readonly, but Eval$() use it from object. str=each(strings) While str Header$=nl$+Eval$(str) End while Assembly$=nl$ \\ insert to line 1 the Header Insert 1 Assembly$=Header$ \\ Also we check for warnings If len(message$)>2 then Assembly$="Warnings: "+nl$+message$ \\ So now we get a report \\ (at each 3/4 of window's lines, the printing stop and wait for user response, any key) Report Assembly$ Clipboard Assembly$ Save.Doc Assembly$, "code.t", Ansi End \\ subs have 10000 limit for recursion but can be extended to 1000000 or more. Sub CodeGenerator(t)   If len(t)=3 then select case t#val(0) Case gSeq CodeGenerator(t#val(1)) : CodeGenerator(t#val(2)) Case gwhile { local spc=pc CodeGenerator(t#val(1)) local pc1=pc pc+=5 ' room for jz CodeGenerator(t#val(2)) data code3$("jz",pc1, pc1, pc+5) data code3$("jmp",pc, pc, spc) pc+=5 ' room for jmp } Case gif { CodeGenerator(t#val(1)) local pc1=pc, pc2 pc+=5 CodeGenerator(t#val(2)#val(1)) If len(t#val(2)#val(2))>0 then pc2=pc pc+=5 data code3$("jz",pc1, pc1, pc) CodeGenerator(t#val(2)#val(2)) data code3$("jmp",pc2, pc2, pc) else data code3$("jz",pc1, pc1, pc) end If } Case gAssign { CodeGenerator(t#val(2)) local newvar_ok=true CodeGenerator(t#val(1)) } case gneg to gnot, gprtc to gprts CodeGenerator(t#val(1)) : data code$(mid$(eval$(t#val(0)),2)) case gmul to gor { CodeGenerator(t#val(1)) CodeGenerator(t#val(2)) data code$(mid$(eval$(t#val(0)),2)) } End select Else.if len(t)=2 then select case t#val(0) Case gString { local spos If exist(strings,t#val$(1)) then spos=eval(strings!) else append strings, t#val$(1) spos=len(strings)-1 end If Push code2$("push",str$(spos,0)) } Case gInt Push code2$("push",t#val$(1), pc) Case gIdentifier { local ipos If exist(dataset,t#val$(1)) then ipos=Eval(dataset!) ' return position else.if newvar_ok then Append dataset, t#val$(1) ipos=len(dataset)-1 else message$="Variable "+t#val$(1)+" not initialized"+nl$   end If If newvar_ok then Push code2$("store","["+str$(ipos, 0)+"]") else Push code2$("fetch","["+str$(ipos, 0)+"]") end If } end select End If End Sub Sub Load_Ast() If i>=lim then Push (,) : exit sub do line$=Trim$(lines$(i)) I++ tok$=piece$(line$," ")(0) until line$<>"" or i>=lim If tok$="Identifier" then Push (gidentifier,trim$(Mid$(line$,11))) else.if tok$="Integer" then long n=Val(Mid$(line$,8)) ' check overflow Push (gint, Trim$(Mid$(line$,8))) else.if tok$="String" then Push (gstring,Trim$(Mid$(line$,7))) else.if tok$=";" then Push (,) Else local otok=symb(tok$) Load_Ast() Load_Ast() Shift 2 Push (otok,array, array) End If End Sub }   CodeGenerator { Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 }  
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Measure a relative performance of sorting algorithms implementations. Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures). Consider three type of input sequences:   ones: sequence of all 1's.   Example: {1, 1, 1, 1, 1}   range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}   shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8} Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm). For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations. Preliminary subtask:   Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort   Query Performance   Write float arrays to a text file   Plot x, y arrays   Polynomial Fitting General steps:   Define sorting routines to be considered.   Define appropriate sequence generators and write timings.   Plot timings.   What conclusions about relative performance of the sorting routines could be made based on the plots?
#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 = len(seq) if size < 2: return seq low, middle, up = partition(seq, random.choice(seq)) return qsortranpart(low) + middle + qsortranpart(up)
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Measure a relative performance of sorting algorithms implementations. Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures). Consider three type of input sequences:   ones: sequence of all 1's.   Example: {1, 1, 1, 1, 1}   range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}   shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8} Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm). For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations. Preliminary subtask:   Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort   Query Performance   Write float arrays to a text file   Plot x, y arrays   Polynomial Fitting General steps:   Define sorting routines to be considered.   Define appropriate sequence generators and write timings.   Plot timings.   What conclusions about relative performance of the sorting routines could be made based on the plots?
#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 /* " " " " " " */ if seed=='' | seed=="," then seed= 1946 /*use a repeatable seed for RANDOM BIF*/ if datatype(seed, 'W') then call random ,,seed /*Specified? Then use as a RANDOM seed*/ kinds= 3; hdr=; #= start# /*hardcoded/fixed number of datum kinds*/ do ra=1 for ranges hdr= hdr || center( commas(#) "numbers", 25)'│' /*(top) header for the output title.*/ do ki=1 for kinds call gen@@ #, ki call set@; call time 'R'; call bubble #; bubble.ra.ki= format(time("E"),,2) call set@; call time 'R'; call cocktail #; cocktail.ra.ki= format(time("E"),,2) call set@; call time 'R'; call cocktailSB #; cocktailSB.ra.ki= format(time("E"),,2) call set@; call time 'R'; call comb #; comb.ra.ki= format(time("E"),,2) call set@; call time 'R'; call exchange #; exchange.ra.ki= format(time("E"),,2) call set@; call time 'R'; call gnome #; gnome.ra.ki= format(time("E"),,2) call set@; call time 'R'; call heap #; heap.ra.ki= format(time("E"),,2) call set@; call time 'R'; call insertion #; insertion.ra.ki= format(time("E"),,2) call set@; call time 'R'; call merge #; merge.ra.ki= format(time("E"),,2) call set@; call time 'R'; call pancake #; pancake.ra.ki= format(time("E"),,2) call set@; call time 'R'; call quick #; quick.ra.ki= format(time("E"),,2) call set@; call time 'R'; call radix #; radix.ra.ki= format(time("E"),,2) call set@; call time 'R'; call selection #; selection.ra.ki= format(time("E"),,2) call set@; call time 'R'; call shell #; shell.ra.ki= format(time("E"),,2) end /*ki*/ #= # + # /*double # elements.*/ end /*ra*/ say; say; say /*say blank sep line*/ say center(' ', 11 ) "│"left(hdr, length(hdr)-1)"│" /*replace last char.*/ reps= ' allONES ascend random │' /*build a title bar.*/ xreps= copies( center(reps, length(reps)), ranges) /*replicate ranges. */ creps= left(xreps, length(xreps)-1)"│" /*replace last char.*/ say center('sort type', 11 ) "│"creps; Lr= length(reps) xcreps= copies( left('', Lr-1, '─')"┼", ranges) say center('' , 12, '─')"┼"left(xcreps, length(xcreps)-1)"┤" call show 'bubble' /* ◄──── show results for bubble sort.*/ call show 'cocktail' /* ◄──── " " " cocktail " */ call show 'cocktailSB' /*+Shifting Bounds*/ /* ◄──── " " " cocktailSB " */ call show 'comb' /* ◄──── " " " comb " */ call show 'exchange' /* ◄──── " " " exchange " */ call show 'gnome' /* ◄──── " " " gnome " */ call show 'heap' /* ◄──── " " " heap " */ call show 'insertion' /* ◄──── " " " insertion " */ call show 'merge' /* ◄──── " " " merge " */ call show 'pancake' /* ◄──── " " " pancake " */ call show 'quick' /* ◄──── " " " quick " */ call show 'radix' /* ◄──── " " " radix " */ call show 'selection' /* ◄──── " " " shell " */ call show 'shell' /* ◄──── " " " shell " */ say translate(center('' , 12, '─')"┴"left(xcreps, length(xcreps)-1)"┘", '┴', "┼") exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? inOrder: parse arg n; do j=1 for n-1; k= j+1; if @.j>@.k then return 0; end; return 1 set@: @.=; do a=1 for #; @.a= @@.a; end; return /*──────────────────────────────────────────────────────────────────────────────────────*/ gen@@: procedure expose @@.; parse arg n,kind; nn= min(n, 100000) /*1e5≡REXX's max.*/ do j=1 for nn; select when kind==1 then @@.j= 1 /*all ones. */ when kind==2 then @@.j= j /*ascending.*/ when kind==3 then @@.j= random(, nn) /*random. */ end /*select*/ end /*j*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ show: parse arg aa; _= left(aa, 11) "│" do ra=1 for ranges do ki=1 for kinds _= _ right( value(aa || . || ra || . || ki), 7, ' ') end /*k*/ _= _ "│" end /*r*/; say _; return /*──────────────────────────────────────────────────────────────────────────────────────*/ bubble: procedure expose @.; parse arg n /*N: is the number of @ elements. */ do m=n-1 by -1 until ok; ok=1 /*keep sorting @ array until done.*/ do j=1 for m; k=j+1; if @.j<[email protected] then iterate /*elements in order? */ [email protected]; @[email protected]; @.k=_; ok=0 /*swap 2 elements; flag as not done.*/ end /*j*/ end /*m*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ cocktail: procedure expose @.; parse arg N; nn= N-1 /*N: is number of items. */ do until done; done= 1 do j=1 for nn; jp= j+1 if @.j>@.jp then do; done=0; [email protected]; @[email protected]; @.jp=_; end end /*j*/ if done then leave /*No swaps done? Finished.*/ do k=nn for nn by -1; kp= k+1 if @.k>@.kp then do; done=0; [email protected]; @[email protected]; @.kp=_; end end /*k*/ end /*until*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ cocktailsb: procedure expose @.; parse arg N /*N: is number of items. */ end$= N - 1; beg$= 1 do while beg$ <= end$ beg$$= end$; end$$= beg$ do j=beg$ to end$; jp= j + 1 if @.j>@.jp then do; [email protected]; @[email protected]; @.jp=_; end$$=j; end end /*j*/ end$= end$$ - 1 do k=end$ to beg$ by -1; kp= k + 1 if @.k>@.kp then do; [email protected]; @[email protected]; @.kp=_; beg$$=k; end end /*k*/ beg$= beg$$ + 1 end /*while*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ comb: procedure expose @.; parse arg n /*N: is the number of @ elements. */ g= n-1 /*G: is the gap between the sort COMBs*/ do until g<=1 & done; done= 1 /*assume sort is done (so far). */ g= g * 0.8  % 1 /*equivalent to: g= trunc( g / 1.25) */ if g==0 then g= 1 /*handle case of the gap is too small. */ do j=1 until $>=n; $= j + g /*$: a temporary index (pointer). */ if @.j>@.$ then do; _= @.j; @.j= @.$; @.$= _; done= 0; end end /*j*/ /* [↑] swap two elements in the array.*/ end /*until*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ exchange: procedure expose @.; parse arg n 1 h /*both N and H have the array size.*/ do while h>1; h= h % 2 do i=1 for n-h; j= i; k= h+i do while @.k<@.j _= @.j; @.j= @.k; @.k= _; if h>=j then leave; j= j-h; k= k-h end /*while @.k<@.j*/ end /*i*/ end /*while h>1*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ gnome: procedure expose @.; parse arg n; k= 2 /*N: is number items. */ do j=3 while k<=n; p= k - 1 /*P: is previous item.*/ if @.p<<[email protected] then do; k= j; iterate; end /*order is OK so far. */ _= @.p; @.p= @.k; @.k= _ /*swap two @ entries. */ k= k - 1; if k==1 then k= j; else j= j-1 /*test for 1st index. */ end /*j*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ heap: procedure expose @.; arg n; do j=n%2 by -1 to 1; call heapS j,n; end /*j*/ do n=n by -1 to 2; _= @.1; @.1= @.n; @.n= _; call heapS 1,n-1 end /*n*/; return /* [↑] swap two elements; and shuffle.*/   heapS: procedure expose @.; parse arg i,n; $= @.i /*obtain parent.*/ do while i+i<=n; j= i+i; k= j+1; if k<=n then if @.k>@.j then j= k if $>[email protected] then leave; @.i= @.j; i= j end /*while*/; @.i= $; return /*define lowest.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ insertion: procedure expose @.; parse arg n do i=2 to n; $= @.i; do j=i-1 by -1 to 1 while @.j>$ _= j + 1; @._= @.j end /*j*/ _= j + 1; @._= $ end /*i*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ merge: procedure expose @. !.; parse arg n, L; if L=='' then do;  !.=; L= 1; end if n==1 then return; h= L + 1 if n==2 then do; if @.L>@.h then do; [email protected]; @[email protected]; @.L=_; end; return; end m= n % 2 /* [↑] handle case of two items.*/ call merge n-m, L+m /*divide items to the left ···*/ call merger m, L, 1 /* " " " " right ···*/ i= 1; j= L + m do k=L while k<j /*whilst items on right exist ···*/ if j==L+n |  !.i<[email protected] then do; @.k= !.i; i= i + 1; end else do; @.k= @.j; j= j + 1; end end /*k*/; return   merger: procedure expose @. !.; parse arg n,L,T if n==1 then do;  !.T= @.L; return; end if n==2 then do; h= L + 1; q= T + 1;  !.q= @.L;  !.T= @.h; return; end m= n % 2 /* [↑] handle case of two items.*/ call merge m, L /*divide items to the left ···*/ call merger n-m, L+m, m+T /* " " " " right ···*/ i= L; j= m + T do k=T while k<j /*whilst items on left exist ···*/ if j==T+n | @.i<=!.j then do;  !.k= @.i; i= i + 1; end else do;  !.k= !.j; j= j + 1; end end /*k*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ pancake: procedure expose @.; parse arg n .; if inOrder(n) then return do n=n by -1 for n-1  != @.1;  ?= 1; do j=2 to n; if @.j<=! then iterate  != @.j;  ?= j end /*j*/ call panFlip ?; call panFlip n end /*n*/; return   panFlip: parse arg y; do i=1 for (y+1)%2; yi=y-i+1; [email protected]; @[email protected]; @.yi=_; end; return /*──────────────────────────────────────────────────────────────────────────────────────*/ quick: procedure expose @.; a.1=1; parse arg b.1; $= 1 /*access @.; get #; define pivot.*/ if inOrder(b.1) then return do while $\==0; L= a.$; t= b.$; $= $-1; if t<2 then iterate H= L+t-1;  ?= L+t%2 if @.H<@.L then if @.?<@.H then do; [email protected]; @[email protected]; end else if @.?>@.L then [email protected] else do; p=@.?; @[email protected]; end else if @.?<@.L then [email protected] else if @.?>@.H then do; [email protected]; @[email protected]; end else do; p=@.?; @[email protected]; end j= L+1; k=h do forever do j=j while j<k & @.j<=p; end /*a tinie─tiny loop.*/ do k=k by -1 while j<k & @.k>=p; end /*another " " */ if j>=k then leave /*segment finished? */ _= @.j; @.j= @.k; @.k= _ /*swap J&K elements.*/ end /*forever*/ $= $+1; k= j-1; @.L= @.k; @.k= p if j<=? then do; a.$= j; b.$= H-j+1; $= $+1; a.$= L; b.$= k-L; end else do; a.$= L; b.$= k-L; $= $+1; a.$= j; b.$= H-j+1; end end /*while $¬==0*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ radix: procedure expose @.; parse arg size,w; mote= c2d(' '); #= 1;  !.#._n= size !.#._b= 1; if w=='' then w= 8 !.#._i= 1; do i=1 for size; [email protected]; @.i= right(abs(y), w, 0); if y<0 then @.i= '-'@.i end /*i*/ /* [↑] negative case.*/   do while #\==0; ctr.= 0; L= 'ffff'x; low= !.#._b; n= !.#._n; $= !.#._i; H= #= #-1 /* [↑] is the radix. */ do j=low for n; parse var @.j =($) _ +1; ctr._= ctr._ + 1 if ctr._==1 & _\=='' then do; if _<<L then L=_; if _>>H then H=_ end /* ↑↑ */ end /*j*/ /* └┴─────◄─── << is a strict comparison.*/ _= /* ┌──◄─── >> " " " " */ if L>>H then iterate /*◄─────┘ */ if L==H & ctr._==0 then do; #= #+1;  !.#._b= low;  !.#._n= n;  !.#._i= $+1; iterate end L= c2d(L); H= c2d(H);  ?= ctr._ + low; top._= ?; ts= mote max= L do k=L to H; _= d2c(k, 1); c= ctr._ /* [↓] swap 2 item radices.*/ if c>ts then parse value c k with ts max;  ?= ?+c; top._= ? end /*k*/ piv= low /*set PIVot to the low part of the sort*/ do while piv<low+n it= @.piv do forever; parse var it =($) _ +1; c= top._ -1 if piv>=c then leave; top._= c;  ?= @.c; @.c= it; it= ? end /*forever*/ top._= piv; @.piv= it; piv= piv + ctr._ end /*while piv<low+n */ i= max do until i==max; _= d2c(i, 1); i= i+1; if i>H then i= L; d= ctr._ if d<=mote then do; if d<2 then iterate; b= top._ do k=b+1 for d-1; q= @.k do j=k-1 by -1 to b while q<<@.j; jp= j+1; @.jp= @.j end /*j*/ jp= j+1; @.jp= q end /*k*/ iterate end #= #+1;  !.#._b= top._;  !.#._n= d;  !.#._i= $ + 1 end /*until i==max*/ end /*while #\==0 */ #= 0 /* [↓↓↓] handle neg. and pos. arrays. */ do i=size by -1 for size; if @.i>=0 then iterate; #= #+1; @@.#= @.i end /*i*/ do j=1 for size; if @.j>=0 then do; #= #+1; @@.#= @.j; end; @.j= @@.j+0 end /*j*/ /* [↑↑↑] combine 2 lists into 1 list. */ return /*──────────────────────────────────────────────────────────────────────────────────────*/ selection: procedure expose @.; parse arg n do j=1 for n-1; _= @.j; p= j do k=j+1 to n; if @.k>=_ then iterate _= @.k; p= k /*this item is out─of─order, swap later*/ end /*k*/ if p==j then iterate /*if the same, the order of items is OK*/ _= @.j; @.j= @.p; @.p= /*swap 2 items that're out─of─sequence.*/ end /*j*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ shell: procedure expose @.; parse arg N /*obtain the N from the argument list*/ i= N % 2 /*% is integer division in REXX. */ do while i\==0 do j=i+1 to N; k= j; p= k-i /*P: previous item*/ _= @.j do while k>=i+1 & @.p>_; @.k= @.p; k= k-i; p= k-i end /*while k≥i+1*/ @.k= _ end /*j*/ if i==2 then i= 1 else i= i * 5 % 11 end /*while i¬==0*/; return
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 | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a parser module/library/class, it would be great if two versions of the solution are provided: One without the parser module, and one with. Grammar The simple programming language to be analyzed is more or less a (very tiny) subset of C. The formal grammar in Extended Backus-Naur Form (EBNF):   stmt_list = {stmt} ;   stmt = ';' | Identifier '=' expr ';' | 'while' paren_expr stmt | 'if' paren_expr stmt ['else' stmt] | 'print' '(' prt_list ')' ';' | 'putc' paren_expr ';' | '{' stmt_list '}'  ;   paren_expr = '(' expr ')' ;   prt_list = (string | expr) {',' (String | expr)} ;   expr = and_expr {'||' and_expr} ; and_expr = equality_expr {'&&' equality_expr} ; equality_expr = relational_expr [('==' | '!=') relational_expr] ; relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ; addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ; multiplication_expr = primary {('*' | '/' | '%') primary } ; primary = Identifier | Integer | '(' expr ')' | ('+' | '-' | '!') primary  ; The resulting AST should be formulated as a Binary Tree. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast The following table shows the input to lex, lex output, and the AST produced by the parser Input to lex Output from lex, input to parse Output from parse count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Specifications List of node type names Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or In the text below, Null/Empty nodes are represented by ";". Non-terminal (internal) nodes For Operators, the following nodes should be created: Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or For each of the above nodes, the left and right sub-nodes are the operands of the respective operation. In pseudo S-Expression format: (Operator expression expression) Negate, Not For these node types, the left node is the operand, and the right node is null. (Operator expression ;) Sequence - sub-nodes are either statements or Sequences. If - left node is the expression, the right node is If node, with it's left node being the if-true statement part, and the right node being the if-false (else) statement part. (If expression (If statement else-statement)) If there is not an else, the tree becomes: (If expression (If statement ;)) Prtc (Prtc (expression) ;) Prts (Prts (String "the string") ;) Prti (Prti (Integer 12345) ;) While - left node is the expression, the right node is the statement. (While expression statement) Assign - left node is the left-hand side of the assignment, the right node is the right-hand side of the assignment. (Assign Identifier expression) Terminal (leaf) nodes: Identifier: (Identifier ident_name) Integer: (Integer 12345) String: (String "Hello World!") ";": Empty node Some simple examples Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path. This simple program: a=11; Produces the following AST, encoded as a binary tree: Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node: (1) Sequence (2) |-- ; (3) |-- Assign (4) |-- Identifier: a (5) |-- Integer: 11 In flattened form: (1) Sequence (2) ; (3) Assign (4) Identifier a (5) Integer 11 This program: a=11; b=22; c=33; Produces the following AST: ( 1) Sequence ( 2) |-- Sequence ( 3) | |-- Sequence ( 4) | | |-- ; ( 5) | | |-- Assign ( 6) | | |-- Identifier: a ( 7) | | |-- Integer: 11 ( 8) | |-- Assign ( 9) | |-- Identifier: b (10) | |-- Integer: 22 (11) |-- Assign (12) |-- Identifier: c (13) |-- Integer: 33 In flattened form: ( 1) Sequence ( 2) Sequence ( 3) Sequence ( 4) ; ( 5) Assign ( 6) Identifier a ( 7) Integer 11 ( 8) Assign ( 9) Identifier b (10) Integer 22 (11) Assign (12) Identifier c (13) Integer 33 Pseudo-code for the parser. Uses Precedence Climbing for expression parsing, and Recursive Descent for statement parsing. The AST is also built: def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error()   while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q))   return x   def paren_expr() expect("(") x = expr(0) expect(")") return x   def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0))   t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t   def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t Once the AST is built, it should be output in a flattened format. This can be as simple as the following def prt_ast(t) if t == NULL print(";\n") else print(t.node_type) if t.node_type in [Identifier, Integer, String] # leaf node print the value of the Ident, Integer or String, "\n" else print("\n") prt_ast(t.left) prt_ast(t.right) If the AST is correctly built, loading it into a subsequent program should be as simple as def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) Finally, the AST can also be tested by running it against one of the AST Interpreter solutions. Test program, assuming this is in a file called prime.t lex <prime.t | parse Input to lex Output from lex, input to parse Output from parse /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 4 1 Identifier count 4 7 Op_assign 4 9 Integer 1 4 10 Semicolon 5 1 Identifier n 5 3 Op_assign 5 5 Integer 1 5 6 Semicolon 6 1 Identifier limit 6 7 Op_assign 6 9 Integer 100 6 12 Semicolon 7 1 Keyword_while 7 7 LeftParen 7 8 Identifier n 7 10 Op_less 7 12 Identifier limit 7 17 RightParen 7 19 LeftBrace 8 5 Identifier k 8 6 Op_assign 8 7 Integer 3 8 8 Semicolon 9 5 Identifier p 9 6 Op_assign 9 7 Integer 1 9 8 Semicolon 10 5 Identifier n 10 6 Op_assign 10 7 Identifier n 10 8 Op_add 10 9 Integer 2 10 10 Semicolon 11 5 Keyword_while 11 11 LeftParen 11 12 LeftParen 11 13 Identifier k 11 14 Op_multiply 11 15 Identifier k 11 16 Op_lessequal 11 18 Identifier n 11 19 RightParen 11 21 Op_and 11 24 LeftParen 11 25 Identifier p 11 26 RightParen 11 27 RightParen 11 29 LeftBrace 12 9 Identifier p 12 10 Op_assign 12 11 Identifier n 12 12 Op_divide 12 13 Identifier k 12 14 Op_multiply 12 15 Identifier k 12 16 Op_notequal 12 18 Identifier n 12 19 Semicolon 13 9 Identifier k 13 10 Op_assign 13 11 Identifier k 13 12 Op_add 13 13 Integer 2 13 14 Semicolon 14 5 RightBrace 15 5 Keyword_if 15 8 LeftParen 15 9 Identifier p 15 10 RightParen 15 12 LeftBrace 16 9 Keyword_print 16 14 LeftParen 16 15 Identifier n 16 16 Comma 16 18 String " is prime\n" 16 31 RightParen 16 32 Semicolon 17 9 Identifier count 17 15 Op_assign 17 17 Identifier count 17 23 Op_add 17 25 Integer 1 17 26 Semicolon 18 5 RightBrace 19 1 RightBrace 20 1 Keyword_print 20 6 LeftParen 20 7 String "Total primes found: " 20 29 Comma 20 31 Identifier count 20 36 Comma 20 38 String "\n" 20 42 RightParen 20 43 Semicolon 21 1 End_of_input Sequence Sequence Sequence Sequence Sequence ; Assign Identifier count Integer 1 Assign Identifier n Integer 1 Assign Identifier limit Integer 100 While Less Identifier n Identifier limit Sequence Sequence Sequence Sequence Sequence ; Assign Identifier k Integer 3 Assign Identifier p Integer 1 Assign Identifier n Add Identifier n Integer 2 While And LessEqual Multiply Identifier k Identifier k Identifier n Identifier p Sequence Sequence ; Assign Identifier p NotEqual Multiply Divide Identifier n Identifier k Identifier k Identifier n Assign Identifier k Add Identifier k Integer 2 If Identifier p If Sequence Sequence ; Sequence Sequence ; Prti Identifier n ; Prts String " is prime\n" ; Assign Identifier count Add Identifier count Integer 1 ; Sequence Sequence Sequence ; Prts String "Total primes found: " ; Prti Identifier count ; Prts String "\n" ; Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#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_Comma, tk_Ident, \ tk_Integer, tk_String = range(31)   nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \ nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \ nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)   # must have same order as above Tokens = [ ["EOI" , False, False, False, -1, -1 ], ["*" , False, True, False, 13, nd_Mul ], ["/" , False, True, False, 13, nd_Div ], ["%" , False, True, False, 13, nd_Mod ], ["+" , False, True, False, 12, nd_Add ], ["-" , False, True, False, 12, nd_Sub ], ["-" , False, False, True, 14, nd_Negate ], ["!" , False, False, True, 14, nd_Not ], ["<" , False, True, False, 10, nd_Lss ], ["<=" , False, True, False, 10, nd_Leq ], [">" , False, True, False, 10, nd_Gtr ], [">=" , False, True, False, 10, nd_Geq ], ["==" , False, True, False, 9, nd_Eql ], ["!=" , False, True, False, 9, nd_Neq ], ["=" , False, False, False, -1, nd_Assign ], ["&&" , False, True, False, 5, nd_And ], ["||" , False, True, False, 4, nd_Or ], ["if" , False, False, False, -1, nd_If ], ["else" , False, False, False, -1, -1 ], ["while" , False, False, False, -1, nd_While ], ["print" , False, False, False, -1, -1 ], ["putc" , False, False, False, -1, -1 ], ["(" , False, False, False, -1, -1 ], [")" , False, False, False, -1, -1 ], ["{" , False, False, False, -1, -1 ], ["}" , False, False, False, -1, -1 ], [";" , False, False, False, -1, -1 ], ["," , False, False, False, -1, -1 ], ["Ident" , False, False, False, -1, nd_Ident ], ["Integer literal" , False, False, False, -1, nd_Integer], ["String literal" , False, False, False, -1, nd_String ] ]   all_syms = {"End_of_input"  : tk_EOI, "Op_multiply"  : tk_Mul, "Op_divide"  : tk_Div, "Op_mod"  : tk_Mod, "Op_add"  : tk_Add, "Op_subtract"  : tk_Sub, "Op_negate"  : tk_Negate, "Op_not"  : tk_Not, "Op_less"  : tk_Lss, "Op_lessequal"  : tk_Leq, "Op_greater"  : tk_Gtr, "Op_greaterequal": tk_Geq, "Op_equal"  : tk_Eql, "Op_notequal"  : tk_Neq, "Op_assign"  : tk_Assign, "Op_and"  : tk_And, "Op_or"  : tk_Or, "Keyword_if"  : tk_If, "Keyword_else"  : tk_Else, "Keyword_while"  : tk_While, "Keyword_print"  : tk_Print, "Keyword_putc"  : tk_Putc, "LeftParen"  : tk_Lparen, "RightParen"  : tk_Rparen, "LeftBrace"  : tk_Lbrace, "RightBrace"  : tk_Rbrace, "Semicolon"  : tk_Semi, "Comma"  : tk_Comma, "Identifier"  : tk_Ident, "Integer"  : tk_Integer, "String"  : tk_String}   Display_nodes = ["Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add", "Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal", "NotEqual", "And", "Or"]   TK_NAME = 0 TK_RIGHT_ASSOC = 1 TK_IS_BINARY = 2 TK_IS_UNARY = 3 TK_PRECEDENCE = 4 TK_NODE = 5   input_file = None err_line = None err_col = None tok = None tok_text = None   #*** show error and exit def error(msg): print("(%d, %d) %s" % (int(err_line), int(err_col), msg)) exit(1)   #*** def gettok(): global err_line, err_col, tok, tok_text, tok_other line = input_file.readline() if len(line) == 0: error("empty line")   line_list = shlex.split(line, False, False) # line col Ident var_name # 0 1 2 3   err_line = line_list[0] err_col = line_list[1] tok_text = line_list[2]   tok = all_syms.get(tok_text) if tok == None: error("Unknown token %s" % (tok_text))   tok_other = None if tok in [tk_Integer, tk_Ident, tk_String]: tok_other = line_list[3]   class Node: def __init__(self, node_type, left = None, right = None, value = None): self.node_type = node_type self.left = left self.right = right self.value = value   #*** def make_node(oper, left, right = None): return Node(oper, left, right)   #*** def make_leaf(oper, n): return Node(oper, value = n)   #*** def expect(msg, s): if tok == s: gettok() return error("%s: Expecting '%s', found '%s'" % (msg, Tokens[s][TK_NAME], Tokens[tok][TK_NAME]))   #*** def expr(p): x = None   if tok == tk_Lparen: x = paren_expr() elif tok in [tk_Sub, tk_Add]: op = (tk_Negate if tok == tk_Sub else tk_Add) gettok() node = expr(Tokens[tk_Negate][TK_PRECEDENCE]) x = (make_node(nd_Negate, node) if op == tk_Negate else node) elif tok == tk_Not: gettok() x = make_node(nd_Not, expr(Tokens[tk_Not][TK_PRECEDENCE])) elif tok == tk_Ident: x = make_leaf(nd_Ident, tok_other) gettok() elif tok == tk_Integer: x = make_leaf(nd_Integer, tok_other) gettok() else: error("Expecting a primary, found: %s" % (Tokens[tok][TK_NAME]))   while Tokens[tok][TK_IS_BINARY] and Tokens[tok][TK_PRECEDENCE] >= p: op = tok gettok() q = Tokens[op][TK_PRECEDENCE] if not Tokens[op][TK_RIGHT_ASSOC]: q += 1   node = expr(q) x = make_node(Tokens[op][TK_NODE], x, node)   return x   #*** def paren_expr(): expect("paren_expr", tk_Lparen) node = expr(0) expect("paren_expr", tk_Rparen) return node   #*** def stmt(): t = None   if tok == tk_If: gettok() e = paren_expr() s = stmt() s2 = None if tok == tk_Else: gettok() s2 = stmt() t = make_node(nd_If, e, make_node(nd_If, s, s2)) elif tok == tk_Putc: gettok() e = paren_expr() t = make_node(nd_Prtc, e) expect("Putc", tk_Semi) elif tok == tk_Print: gettok() expect("Print", tk_Lparen) while True: if tok == tk_String: e = make_node(nd_Prts, make_leaf(nd_String, tok_other)) gettok() else: e = make_node(nd_Prti, expr(0))   t = make_node(nd_Sequence, t, e) if tok != tk_Comma: break gettok() expect("Print", tk_Rparen) expect("Print", tk_Semi) elif tok == tk_Semi: gettok() elif tok == tk_Ident: v = make_leaf(nd_Ident, tok_other) gettok() expect("assign", tk_Assign) e = expr(0) t = make_node(nd_Assign, v, e) expect("assign", tk_Semi) elif tok == tk_While: gettok() e = paren_expr() s = stmt() t = make_node(nd_While, e, s) elif tok == tk_Lbrace: gettok() while tok != tk_Rbrace and tok != tk_EOI: t = make_node(nd_Sequence, t, stmt()) expect("Lbrace", tk_Rbrace) elif tok == tk_EOI: pass else: error("Expecting start of statement, found: %s" % (Tokens[tok][TK_NAME]))   return t   #*** def parse(): t = None gettok() while True: t = make_node(nd_Sequence, t, stmt()) if tok == tk_EOI or t == None: break return t   def prt_ast(t): if t == None: print(";") else: print("%-14s" % (Display_nodes[t.node_type]), end='') if t.node_type in [nd_Ident, nd_Integer]: print("%s" % (t.value)) elif t.node_type == nd_String: print("%s" %(t.value)) else: print("") prt_ast(t.left) prt_ast(t.right)   #*** main driver input_file = sys.stdin if len(sys.argv) > 1: try: input_file = open(sys.argv[1], "r", 4096) except IOError as e: error(0, 0, "Can't open %s" % sys.argv[1]) t = parse() prt_ast(t)
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)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#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 State(x, y: Integer): boolean; class function NewField(w1, h1: Integer): TField; static; end;   TLife = record a, b: TField; w, h: Integer; class function NewLife(w1, h1: Integer): TLife; static; procedure Step; function ToString: string; end;   { TField }   class function TField.NewField(w1, h1: Integer): TField; var s1: TBoolMatrix; begin SetLength(s1, h1); for var i := 0 to High(s1) do SetLength(s1[i], w1); with Result do begin s := s1; w := w1; h := h1; end; end;   function TField.Next(x, y: Integer): boolean; var _on: Integer; begin _on := 0; for var i := -1 to 1 do for var j := -1 to 1 do if self.State(x + i, y + j) and not ((j = 0) and (i = 0)) then inc(_on); Result := (_on = 3) or (_on = 2) and self.State(x, y); end;   procedure TField.SetValue(x, y: Integer; b: boolean); begin self.s[y, x] := b; end;   function TField.State(x, y: Integer): boolean; begin while y < 0 do inc(y, self.h); while x < 0 do inc(x, self.w); result := self.s[y mod self.h, x mod self.w] end;   { TLife }   class function TLife.NewLife(w1, h1: Integer): TLife; var a1: TField; begin a1 := TField.NewField(w1, h1); for var i := 0 to (w1 * h1 div 2) do a1.SetValue(Random(w1), Random(h1), True); with Result do begin a := a1; b := TField.NewField(w1, h1); w := w1; h := h1; end; end;   procedure TLife.Step; var tmp: TField; begin for var y := 0 to self.h - 1 do for var x := 0 to self.w - 1 do self.b.SetValue(x, y, self.a.Next(x, y)); tmp := self.a; self.a := self.b; self.b := tmp; end;   function TLife.ToString: string; begin result := ''; for var y := 0 to self.h - 1 do begin for var x := 0 to self.w - 1 do begin var b: char := ' '; if self.a.State(x, y) then b := '*'; result := result + b; end; result := result + #10; end; end;   begin Randomize;   var life := TLife.NewLife(80, 15);   for var i := 1 to 300 do begin life.Step; ClrScr; writeln(life.ToString); sleep(30); end; readln; end.
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 See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Ring
Ring
  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 See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Ruby
Ruby
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}"} #=> x : 2 #=> y : 5
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 if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#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 statement(s) else statement(s) end if while boolean_expr statement(s) end while
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 programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   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 of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#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 do s[k+1..k] = sep end for exit end if end for exit end if end for printf(1,"%s\n",{s}) end procedure commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231"," ",6,5) commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",".") commatize("\"-in Aus$+1411.8millions\"") commatize("===US$0017440 millions=== (in 2000 dollars)") commatize("123.e8000 is pretty big.") commatize("The land area of the earth is 57268900(29% of the surface) square miles.") commatize("Ain't no numbers in this here words, nohow, no way, Jose.") commatize("James was never known as 0000000007") commatize("Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.") commatize(" $-140000±100 millions.") commatize("6/9/1946 was a good year for some.")
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 programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   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 of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#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[:_startPos] periods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ] outString += leadIn + _separator.join( periods ) else: outString += match   strPos += len( match )   return outString       print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) ) print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." )) print ( Commatize( "\"-in Aus$+1411.8millions\"" )) print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" )) print ( Commatize( "123.e8000 is pretty big." )) print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." )) print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." )) print ( Commatize( "James was never known as 0000000007" )) print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." )) print ( Commatize( "␢␢␢$-140000±100 millions." )) print ( Commatize( "6/9/1946 was a good year for some." ))  
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 the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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; 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. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#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 {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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],donuts[i]) } arr[key]++ } } cmd = "SORT" for (i in arr) { printf("%s\n",i) | cmd choices++ } close(cmd) printf("choices = %d\n",choices) exit(0) }  
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 Permutation. 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) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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));   enum bigPermutation = (in uint n, in uint k) => exp(logGamma(n + 1) - logGamma(n - k + 1));   enum bigCombination = (in uint n, in uint k) => exp(logGamma(n + 1) - logGamma(n - k + 1) - logGamma(k + 1));   void main() { 12.permutation(9).writeln; 12.bigPermutation(9).writeln; 60.combination(53).writeln; 145.bigPermutation(133).writeln; 900.bigCombination(450).writeln; 1_000.bigCombination(969).writeln; 15_000.bigPermutation(73).writeln; 15_000.bigPermutation(1185).writeln; writefln("%(%s\\\n%)", 15_000.permutation(74).text.chunks(50)); }
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 also used to refer to the first stage of a lexer). Task[edit] Create a lexical analyzer for the simple programming language specified below. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a lexer module/library/class, it would be great if two versions of the solution are provided: One without the lexer module, and one with. Input Specification The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens: Operators Name Common name Character sequence Op_multiply multiply * Op_divide divide / Op_mod mod % Op_add plus + Op_subtract minus - Op_negate unary minus - Op_less less than < Op_lessequal less than or equal <= Op_greater greater than > Op_greaterequal greater than or equal >= Op_equal equal == Op_notequal not equal != Op_not unary not ! Op_assign assignment = Op_and logical and && Op_or logical or ¦¦ The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task. Symbols Name Common name Character LeftParen left parenthesis ( RightParen right parenthesis ) LeftBrace left brace { RightBrace right brace } Semicolon semi-colon ; Comma comma , Keywords Name Character sequence Keyword_if if Keyword_else else Keyword_while while Keyword_print print Keyword_putc putc Identifiers and literals These differ from the the previous tokens, in that each occurrence of them has a value associated with it. Name Common name Format description Format regex Value Identifier identifier one or more letter/number/underscore characters, but not starting with a number [_a-zA-Z][_a-zA-Z0-9]* as is Integer integer literal one or more digits [0-9]+ as is, interpreted as a number Integer char literal exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes '([^'\n]|\\n|\\\\)' the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n' String string literal zero or more characters (anything except newline or double quote), enclosed by double quotes "[^"\n]*" the characters without the double quotes and with escape sequences converted For char and string literals, the \n escape sequence is supported to represent a new-line character. For char and string literals, to represent a backslash, use \\. No other special sequences are supported. This means that: Char literals cannot represent a single quote character (value 39). String literals cannot represent strings containing double quote characters. Zero-width tokens Name Location End_of_input when the end of the input stream is reached White space Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below. "Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =). Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge. This means: keywords, identifiers, and integer literals. e.g. ifprint is recognized as an identifier, instead of the keywords if and print. e.g. 42fred is invalid, and neither recognized as a number nor an identifier. Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value). e.g. & & is invalid, and not interpreted as the && operator. For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions: if ( p /* meaning n is prime */ ) { print ( n , " " ) ; count = count + 1 ; /* number of primes found so far */ } if(p){print(n," ");count=count+1;} Complete list of token names 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_notequal Op_assign Op_and Op_or Keyword_if Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen LeftBrace RightBrace Semicolon Comma Identifier Integer String Output Format The program output should be a sequence of lines, each consisting of the following whitespace-separated fields: the line number where the token starts the column number where the token starts the token name the token value (only for Identifier, Integer, and String tokens) the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement. This task is intended to be used as part of a pipeline, with the other compiler tasks - for example: lex < hello.t | parse | gen | vm Or possibly: lex hello.t lex.out parse lex.out parse.out gen parse.out gen.out vm gen.out This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs. Diagnostics The following error conditions should be caught: Error Example Empty character constant '' Unknown escape sequence. \r Multi-character constant. 'xx' End-of-file in comment. Closing comment characters not found. End-of-file while scanning string literal. Closing string character not found. End-of-line while scanning string literal. Closing string character not found before end-of-line. Unrecognized character. | Invalid number. Starts like a number, but ends in non-numeric characters. 123abc Test Cases Input Output Test Case 1: /* Hello world */ print("Hello, World!\n"); 4 1 Keyword_print 4 6 LeftParen 4 7 String "Hello, World!\n" 4 24 RightParen 4 25 Semicolon 5 1 End_of_input Test Case 2: /* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, "\n"); 4 1 Identifier phoenix_number 4 16 Op_assign 4 18 Integer 142857 4 24 Semicolon 5 1 Keyword_print 5 6 LeftParen 5 7 Identifier phoenix_number 5 21 Comma 5 23 String "\n" 5 27 RightParen 5 28 Semicolon 6 1 End_of_input Test Case 3: /* All lexical tokens - not syntactically correct, but that will have to wait until syntax analysis */ /* Print */ print /* Sub */ - /* Putc */ putc /* Lss */ < /* If */ if /* Gtr */ > /* Else */ else /* Leq */ <= /* While */ while /* Geq */ >= /* Lbrace */ { /* Eq */ == /* Rbrace */ } /* Neq */ != /* Lparen */ ( /* And */ && /* Rparen */ ) /* Or */ || /* Uminus */ - /* Semi */ ; /* Not */ ! /* Comma */ , /* Mul */ * /* Assign */ = /* Div */ / /* Integer */ 42 /* Mod */ % /* String */ "String literal" /* Add */ + /* Ident */ variable_name /* character literal */ '\n' /* character literal */ '\\' /* character literal */ ' ' 5 16 Keyword_print 5 40 Op_subtract 6 16 Keyword_putc 6 40 Op_less 7 16 Keyword_if 7 40 Op_greater 8 16 Keyword_else 8 40 Op_lessequal 9 16 Keyword_while 9 40 Op_greaterequal 10 16 LeftBrace 10 40 Op_equal 11 16 RightBrace 11 40 Op_notequal 12 16 LeftParen 12 40 Op_and 13 16 RightParen 13 40 Op_or 14 16 Op_subtract 14 40 Semicolon 15 16 Op_not 15 40 Comma 16 16 Op_multiply 16 40 Op_assign 17 16 Op_divide 17 40 Integer 42 18 16 Op_mod 18 40 String "String literal" 19 16 Op_add 19 40 Identifier variable_name 20 26 Integer 10 21 26 Integer 92 22 26 Integer 32 23 1 End_of_input Test Case 4: /*** test printing, embedded \n and comments with lots of '*' ***/ print(42); print("\nHello World\nGood Bye\nok\n"); print("Print a slash n - \\n.\n"); 2 1 Keyword_print 2 6 LeftParen 2 7 Integer 42 2 9 RightParen 2 10 Semicolon 3 1 Keyword_print 3 6 LeftParen 3 7 String "\nHello World\nGood Bye\nok\n" 3 38 RightParen 3 39 Semicolon 4 1 Keyword_print 4 6 LeftParen 4 7 String "Print a slash n - \\n.\n" 4 33 RightParen 4 34 Semicolon 5 1 End_of_input Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Syntax Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#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> #include <utility> // std::forward #include <variant> // TokenVal   using namespace std;   // ===================================================================================================================== // Machinery // ===================================================================================================================== string file_to_string (const string& path) { // Open file ifstream file {path, ios::in | ios::binary | ios::ate}; if (!file) throw (errno);   // Allocate string memory string contents; contents.resize(file.tellg());   // Read file contents into string file.seekg(0); file.read(contents.data(), contents.size());   return contents; }   void string_to_file (const string& path, string contents) { ofstream file {path, ios::out | ios::binary}; if (!file) throw (errno);   file.write(contents.data(), contents.size()); }   template <class F> void with_IO (string source, string destination, F&& f) { string input;   if (source == "stdin") getline(cin, input); else input = file_to_string(source);   string output = invoke(forward<F>(f), input);   if (destination == "stdout") cout << output; else string_to_file(destination, output); }   // Add escaped newlines and backslashes back in for printing string sanitize (string s) { for (auto i = 0u; i < s.size(); ++i) { if (s[i] == '\n') s.replace(i++, 1, "\\n"); else if (s[i] == '\\') s.replace(i++, 1, "\\\\"); }   return s; }   class Scanner { public: const char* pos; int line = 1; int column = 1;   Scanner (const char* source) : pos {source} {}   inline char peek () { return *pos; }   void advance () { if (*pos == '\n') { ++line; column = 1; } else ++column;   ++pos; }   char next () { advance(); return peek(); }   void skip_whitespace () { while (isspace(static_cast<unsigned char>(peek()))) advance(); } }; // class Scanner     // ===================================================================================================================== // Tokens // ===================================================================================================================== enum class TokenName { OP_MULTIPLY, OP_DIVIDE, OP_MOD, OP_ADD, OP_SUBTRACT, OP_NEGATE, OP_LESS, OP_LESSEQUAL, OP_GREATER, OP_GREATEREQUAL, OP_EQUAL, OP_NOTEQUAL, OP_NOT, OP_ASSIGN, OP_AND, OP_OR, LEFTPAREN, RIGHTPAREN, LEFTBRACE, RIGHTBRACE, SEMICOLON, COMMA, KEYWORD_IF, KEYWORD_ELSE, KEYWORD_WHILE, KEYWORD_PRINT, KEYWORD_PUTC, IDENTIFIER, INTEGER, STRING, END_OF_INPUT, ERROR };   using TokenVal = variant<int, string>;   struct Token { TokenName name; TokenVal value; int line; int column; };     const char* to_cstring (TokenName name) { static const char* s[] = { "Op_multiply", "Op_divide", "Op_mod", "Op_add", "Op_subtract", "Op_negate", "Op_less", "Op_lessequal", "Op_greater", "Op_greaterequal", "Op_equal", "Op_notequal", "Op_not", "Op_assign", "Op_and", "Op_or", "LeftParen", "RightParen", "LeftBrace", "RightBrace", "Semicolon", "Comma", "Keyword_if", "Keyword_else", "Keyword_while", "Keyword_print", "Keyword_putc", "Identifier", "Integer", "String", "End_of_input", "Error" };   return s[static_cast<int>(name)]; }     string to_string (Token t) { ostringstream out; out << setw(2) << t.line << " " << setw(2) << t.column << " ";   switch (t.name) { case (TokenName::IDENTIFIER) : out << "Identifier " << get<string>(t.value); break; case (TokenName::INTEGER) : out << "Integer " << left << get<int>(t.value); break; case (TokenName::STRING) : out << "String \"" << sanitize(get<string>(t.value)) << '"'; break; case (TokenName::END_OF_INPUT) : out << "End_of_input"; break; case (TokenName::ERROR) : out << "Error " << get<string>(t.value); break; default : out << to_cstring(t.name); }   out << '\n';   return out.str(); }     // ===================================================================================================================== // Lexer // ===================================================================================================================== class Lexer { public: Lexer (const char* source) : s {source}, pre_state {s} {}   bool has_more () { return s.peek() != '\0'; }   Token next_token () { s.skip_whitespace();   pre_state = s;   switch (s.peek()) { case '*' : return simply(TokenName::OP_MULTIPLY); case '%' : return simply(TokenName::OP_MOD); case '+' : return simply(TokenName::OP_ADD); case '-' : return simply(TokenName::OP_SUBTRACT); case '{' : return simply(TokenName::LEFTBRACE); case '}' : return simply(TokenName::RIGHTBRACE); case '(' : return simply(TokenName::LEFTPAREN); case ')' : return simply(TokenName::RIGHTPAREN); case ';' : return simply(TokenName::SEMICOLON); case ',' : return simply(TokenName::COMMA); case '&' : return expect('&', TokenName::OP_AND); case '|' : return expect('|', TokenName::OP_OR); case '<' : return follow('=', TokenName::OP_LESSEQUAL, TokenName::OP_LESS); case '>' : return follow('=', TokenName::OP_GREATEREQUAL, TokenName::OP_GREATER); case '=' : return follow('=', TokenName::OP_EQUAL, TokenName::OP_ASSIGN); case '!' : return follow('=', TokenName::OP_NOTEQUAL, TokenName::OP_NOT); case '/' : return divide_or_comment(); case '\'' : return char_lit(); case '"' : return string_lit();   default : if (is_id_start(s.peek())) return identifier(); if (is_digit(s.peek())) return integer_lit(); return error("Unrecognized character '", s.peek(), "'");   case '\0' : return make_token(TokenName::END_OF_INPUT); } }     private: Scanner s; Scanner pre_state; static const map<string, TokenName> keywords;     template <class... Args> Token error (Args&&... ostream_args) { string code {pre_state.pos, (string::size_type) s.column - pre_state.column};   ostringstream msg; (msg << ... << forward<Args>(ostream_args)) << '\n' << string(28, ' ') << "(" << s.line << ", " << s.column << "): " << code;   if (s.peek() != '\0') s.advance();   return make_token(TokenName::ERROR, msg.str()); }     inline Token make_token (TokenName name, TokenVal value = 0) { return {name, value, pre_state.line, pre_state.column}; }     Token simply (TokenName name) { s.advance(); return make_token(name); }     Token expect (char expected, TokenName name) { if (s.next() == expected) return simply(name); else return error("Unrecognized character '", s.peek(), "'"); }     Token follow (char expected, TokenName ifyes, TokenName ifno) { if (s.next() == expected) return simply(ifyes); else return make_token(ifno); }     Token divide_or_comment () { if (s.next() != '*') return make_token(TokenName::OP_DIVIDE);   while (s.next() != '\0') { if (s.peek() == '*' && s.next() == '/') { s.advance(); return next_token(); } }   return error("End-of-file in comment. Closing comment characters not found."); }     Token char_lit () { int n = s.next();   if (n == '\'') return error("Empty character constant");   if (n == '\\') switch (s.next()) { case 'n' : n = '\n'; break; case '\\' : n = '\\'; break; default : return error("Unknown escape sequence \\", s.peek()); }   if (s.next() != '\'') return error("Multi-character constant");   s.advance(); return make_token(TokenName::INTEGER, n); }     Token string_lit () { string text = "";   while (s.next() != '"') switch (s.peek()) { case '\\' : switch (s.next()) { case 'n' : text += '\n'; continue; case '\\' : text += '\\'; continue; default : return error("Unknown escape sequence \\", s.peek()); }   case '\n' : return error("End-of-line while scanning string literal." " Closing string character not found before end-of-line.");   case '\0' : return error("End-of-file while scanning string literal." " Closing string character not found.");   default : text += s.peek(); }   s.advance(); return make_token(TokenName::STRING, text); }     static inline bool is_id_start (char c) { return isalpha(static_cast<unsigned char>(c)) || c == '_'; } static inline bool is_id_end (char c) { return isalnum(static_cast<unsigned char>(c)) || c == '_'; } static inline bool is_digit (char c) { return isdigit(static_cast<unsigned char>(c)); }     Token identifier () { string text (1, s.peek());   while (is_id_end(s.next())) text += s.peek();   auto i = keywords.find(text); if (i != keywords.end()) return make_token(i->second);   return make_token(TokenName::IDENTIFIER, text); }     Token integer_lit () { while (is_digit(s.next()));   if (is_id_start(s.peek())) return error("Invalid number. Starts like a number, but ends in non-numeric characters.");   int n;   auto r = from_chars(pre_state.pos, s.pos, n); if (r.ec == errc::result_out_of_range) return error("Number exceeds maximum value");   return make_token(TokenName::INTEGER, n); } }; // class Lexer     const map<string, TokenName> Lexer::keywords = { {"else", TokenName::KEYWORD_ELSE}, {"if", TokenName::KEYWORD_IF}, {"print", TokenName::KEYWORD_PRINT}, {"putc", TokenName::KEYWORD_PUTC}, {"while", TokenName::KEYWORD_WHILE} };     int main (int argc, char* argv[]) { string in = (argc > 1) ? argv[1] : "stdin"; string out = (argc > 2) ? argv[2] : "stdout";   with_IO(in, out, [](string input) { Lexer lexer {input.data()};   string s = "Location Token name Value\n" "--------------------------------------\n";   while (lexer.has_more()) s += to_string(lexer.next_token()); return s; }); }  
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:edx fd:edi -- ) 1 syscall ordie ; : print ( buf len -- ) stdout write ;   : newline ( -- ) s" \n" print ; : println ( buf len -- ) print newline ;   : find0 ( start:rsi -- end:rsi ) lodsb 0 cmp latest xne ; : cstrlen ( str:rdi -- len:rsi ) dup find0 swap sub dec ; : cstr>str ( cstr:rdx -- str:rsi len:rdx ) dup cstrlen xchg ;   : print-arg ( arg -- ) cstr>str println ;   : _start ( rsp -- noret ) dup @ swap : print-args ( argc:rcx argv:rsp -- noret ) 8 add @ print-arg latest loop bye ;  
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, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#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) }   if 1 <= *args then { f_inp := FileStream(args[1], FileOpt.RDONLY) | stop (&why) } else { f_inp := FileStream.stdin } f_inp := BufferStream(f_inp)   if 2 <= *args then { f_out := FileStream(args[2], ior (FileOpt.WRONLY, FileOpt.TRUNC, FileOpt.CREAT)) | stop (&why) } else { f_out := FileStream.stdout }   vm := VirtualMachine() vm.read_assembly_code(f_inp) vm.run(f_out) end   procedure int2bytes (n) local bytes   # The VM is little-endian.   bytes := "****" bytes[1] := char (iand(n, 16rFF)) bytes[2] := char(iand(ishift(n, -8), 16rFF)) bytes[3] := char(iand(ishift(n, -16), 16rFF)) bytes[4] := char(iand(ishift(n, -24), 16rFF)) return bytes end   procedure bytes2int(bytes, i) local n0, n1, n2, n3, n   # The VM is little-endian.   n0 := ord(bytes[i]) n1 := ishift(ord(bytes[i + 1]), 8) n2 := ishift(ord(bytes[i + 2]), 16) n3 := ishift(ord(bytes[i + 3]), 24) n := ior (n0, ior (n1, ior (n2, n3)))   # Do not forget to extend the sign bit. return (if n3 <= 16r7F then n else ior(n, icom(16rFFFFFFFF))) end   class OpcodeCollection()   public static const opcode_names public static const opcode_values   public static const op_halt public static const op_add public static const op_sub public static const op_mul public static const op_div public static const op_mod public static const op_lt public static const op_gt public static const op_le public static const op_ge public static const op_eq public static const op_ne public static const op_and public static const op_or public static const op_neg public static const op_not public static const op_prtc public static const op_prti public static const op_prts public static const op_fetch public static const op_store public static const op_push public static const op_jmp public static const op_jz   private static init() local i   opcode_names := ["halt", "add", "sub", "mul", "div", "mod", "lt", "gt", "le", "ge", "eq", "ne", "and", "or", "neg", "not", "prtc", "prti", "prts", "fetch", "store", "push", "jmp", "jz"]   opcode_values := table() every i := 1 to *opcode_names do opcode_values[opcode_names[i]] := char(i)   op_halt := opcode_values["halt"] op_add := opcode_values["add"] op_sub := opcode_values["sub"] op_mul := opcode_values["mul"] op_div := opcode_values["div"] op_mod := opcode_values["mod"] op_lt := opcode_values["lt"] op_gt := opcode_values["gt"] op_le := opcode_values["le"] op_ge := opcode_values["ge"] op_eq := opcode_values["eq"] op_ne := opcode_values["ne"] op_and := opcode_values["and"] op_or := opcode_values["or"] op_neg := opcode_values["neg"] op_not := opcode_values["not"] op_prtc := opcode_values["prtc"] op_prti := opcode_values["prti"] op_prts := opcode_values["prts"] op_fetch := opcode_values["fetch"] op_store := opcode_values["store"] op_push := opcode_values["push"] op_jmp := opcode_values["jmp"] op_jz := opcode_values["jz"]   return end   end   class VirtualMachine(OpcodeCollection)   public code public global_data public strings public stack public pc   private static const whitespace_chars   private static init() whitespace_chars := ' \t\n\r\f\v' return end   public read_assembly_code(f) local data_size, number_of_strings local line, ch local i local address local opcode   # Read the header line. line := f.read() | bad_vm() line ? { tab(many(whitespace_chars)) tab(match("Datasize")) | bad_vm() tab(many(whitespace_chars)) tab(any(':')) | bad_vm() tab(many(whitespace_chars)) data_size := integer(tab(many(&digits))) | bad_vm() tab(many(whitespace_chars)) tab(match("Strings")) | bad_vm() tab(many(whitespace_chars)) tab(any(':')) | bad_vm() tab(many(whitespace_chars)) number_of_strings := integer(tab(many(&digits))) | bad_vm() }   # Read the strings. strings := list(number_of_strings) every i := 1 to number_of_strings do { strings[i] := "" line := f.read() | bad_vm() line ? { tab(many(whitespace_chars)) tab(any('"')) | bad_vm() while ch := tab(any(~'"')) do { if ch == '\\' then { ch := tab(any('n\\')) | bad_vm() strings[i] ||:= (if (ch == "n") then "\n" else "\\") } else { strings[i] ||:= ch } } } }   # Read the code. code := "" while line := f.read() do { line ? { tab(many(whitespace_chars)) address := integer(tab(many(&digits))) | bad_vm() tab(many(whitespace_chars)) opcode := tab(many(~whitespace_chars)) | bad_vm() code ||:= opcode_values[opcode] case opcode of { "push": { tab(many(whitespace_chars)) code ||:= int2bytes(integer(tab(many(&digits)))) | int2bytes(integer(tab(any('-')) || tab(many(&digits)))) | bad_vm() } "fetch" | "store": { tab(many(whitespace_chars)) tab(any('[')) | bad_vm() tab(many(whitespace_chars)) code ||:= int2bytes(integer(tab(many(&digits)))) | bad_vm() tab(many(whitespace_chars)) tab(any(']')) | bad_vm() } "jmp" | "jz": { tab(many(whitespace_chars)) tab(any('(')) | bad_vm() tab(many(whitespace_chars)) code ||:= int2bytes(integer(tab(many(&digits)))) | int2bytes(integer(tab(any('-')) || tab(many(&digits)))) | bad_vm() tab(many(whitespace_chars)) tab(any(')')) | bad_vm() tab(many(whitespace_chars)) tab(many(&digits)) | bad_vm() } default: { # Do nothing } } } }   # Create a global data area. global_data := list(data_size, &null)   initialize()   return end   public run(f_out) initialize() continue(f_out) return end   public continue(f_out) while code[pc] ~== op_halt do step(f_out) end   public step(f_out) local opcode   opcode := code[pc] pc +:= 1 case opcode of { op_add: binop("+") op_sub: binop("-") op_mul: binop("*") op_div: binop("/") op_mod: binop("%") op_lt: comparison("<") op_gt: comparison(">") op_le: comparison("<=") op_ge: comparison(">=") op_eq: comparison("=") op_ne: comparison("~=") op_and: logical_and() op_or: logical_or() op_neg: negate() op_not: logical_not() op_prtc: printc(f_out) op_prti: printi(f_out) op_prts: prints(f_out) op_fetch: fetch_global() op_store: store_global() op_push: push_argument() op_jmp: jump() op_jz: jump_if_zero() default: bad_opcode() } end   private negate() stack[1] := -stack[1] return end   private binop(func) stack[2] := func(stack[2], stack[1]) pop(stack) return end   private comparison(func) stack[2] := (if func(stack[2], stack[1]) then 1 else 0) pop(stack) return end   private logical_and() stack[2] := (if stack[2] ~= 0 & stack[1] ~= 0 then 1 else 0) pop(stack) return end   private logical_or() stack[2] := (if stack[2] ~= 0 | stack[1] ~= 0 then 1 else 0) pop(stack) return end   private logical_not() stack[1] := (if stack[1] ~= 0 then 0 else 1) return end   private printc(f_out) /f_out := FileStream.stdout f_out.writes(char(pop(stack))) return end   private printi(f_out) /f_out := FileStream.stdout f_out.writes(pop(stack)) return end   private prints(f_out) /f_out := FileStream.stdout f_out.writes(strings[pop(stack) + 1]) return end   private fetch_global() push(stack, global_data[get_argument() + 1]) pc +:= 4 return end   private store_global() global_data[get_argument() + 1] := pop(stack) pc +:= 4 return end   private push_argument() push(stack, get_argument()) pc +:= 4 return end   private jump() pc +:= get_argument() return end   private jump_if_zero() if pop(stack) = 0 then pc +:= get_argument() else pc +:= 4 return end   private get_argument() return bytes2int(code, pc) end   public initialize() # The program counter starts at 1, for convenient indexing into # the code[] array. Icon indexing starts at 1 (for a *very* good # reason, but that’s a topic for another day). pc := 1 stack := [] return end   private bad_vm() write(FileStream.stderr, "Bad VM.") exit(1) end   private bad_opcode() write(FileStream.stderr, "Bad opcode.") exit(1) end end
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 Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#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" nPrts = "Prts" nPrti = "Prti" nWhile = "While" nAssign = "Assign" nNegate = "Negate" nNot = "Not" nMultiply = "Multiply" nDivide = "Divide" nMod = "Mod" nAdd = "Add" nSubtract = "Subtract" nLess = "Less" nLessEqual = "LessEqual" nGreater = "Greater" nGreaterEqual = "GreaterEqual" nEqual = "Equal" nNotEqual = "NotEqual" nAnd = "And" nOr = "Or"   # Ast node description. Node = ref object left: Node right: Node case kind: NodeKind of nString: stringVal: string of nInteger: intVal: int of nIdentifier: name: string else: nil   # Virtual machine opcodes. OpCode = enum opFetch = "fetch" opStore = "store" opPush = "push" opJmp = "jmp" opJz = "jz" opAdd = "add" opSub = "sub" opMul = "mul" opDiv = "div" opMod = "mod" opLt = "lt" opgt = "gt" opLe = "le" opGe = "ge" opEq = "eq" opNe = "ne" opAnd = "and" opOr = "or" opNeg = "neg" opNot = "not" opPrtc = "prtc" opPrti = "prti" opPrts = "prts" opHalt = "halt" opInvalid = "invalid"   # Code generator context. CodeGen = object address: int # Current address in code part. instr: seq[string] # List of instructions. vars: Table[string, int] # Mapping variable name -> variable index. strings: seq[string] # List of strings.   # Node ranges. UnaryOpNode = range[nNegate..nNot] BinaryOpNode = range[nMultiply..nOr] PrintNode = range[nPrtc..nPrti]     const   # Mapping unary operator Node -> OpCode. UnOp: array[UnaryOpNode, OpCode] = [opNeg, opNot]   # Mapping binary operator Node -> OpCode. BinOp: array[BinaryOpNode, OpCode] = [opMul, opDiv, opMod, opAdd, opSub, opLt, opLe, opGt, opGe, opEq, opNe, opAnd, opOr]   # Mapping print Node -> OpCode. PrintOp: array[PrintNode, OpCode] = [opPrtc, opPrts, opPrti]     #################################################################################################### # Code generator.   proc genSimpleInst(gen: var CodeGen; opcode: OpCode) = ## Build a simple instruction (no operand). gen.instr.add &"{gen.address:>5} {opcode}"   #---------------------------------------------------------------------------------------------------   proc genMemInst(gen: var CodeGen; opcode: OpCode; memIndex: int) = ## Build a memory access instruction (opFetch, opStore). gen.instr.add &"{gen.address:>5} {opcode:<5} [{memIndex}]"   #---------------------------------------------------------------------------------------------------   proc genJumpInst(gen: var CodeGen; opcode: OpCode): int = ## Build a jump instruction. We use the letters X and Y as placeholders ## for the offset and the target address. result = gen.instr.len gen.instr.add &"{gen.address:>5} {opcode:<5} (X) Y"   #---------------------------------------------------------------------------------------------------   proc genPush(gen: var CodeGen; value: int) = ## Build a push instruction. gen.instr.add &"{gen.address:>5} {opPush:<5} {value}"   #---------------------------------------------------------------------------------------------------   proc updateJumpInst(gen: var CodeGen; index: int; jumpAddress, targetAddress: int) = ## Update the offset and the target address of a jump instruction.   var instr {.byAddr.} = gen.instr[index] let offset = targetAddress - jumpAddress - 1 for idx in countdown(instr.high, 0): case instr[idx] of 'Y': instr[idx..idx] = $targetAddress of 'X': instr[idx..idx] = $offset break else: discard   #---------------------------------------------------------------------------------------------------   proc process(gen: var CodeGen; node: Node) = ## Generate code for a node.   if node.isNil: return   case node.kind:   of nInteger: gen.genPush(node.intVal) inc gen.address, 5   of nIdentifier: if node.name notin gen.vars: gen.vars[node.name] = gen.vars.len gen.genMemInst(opFetch, gen.vars[node.name]) inc gen.address, 5   of nString: var index = gen.strings.find(node.stringVal) if index < 0: index = gen.strings.len gen.strings.add(node.stringVal) gen.genPush(index) inc gen.address, 5   of nAssign: gen.process(node.right) if node.left.name notin gen.vars: gen.vars[node.left.name] = gen.vars.len gen.genMemInst(opStore, gen.vars[node.left.name]) inc gen.address, 5   of UnaryOpNode.low..UnaryOpNode.high: gen.process(node.left) gen.genSimpleInst(UnOp[node.kind]) inc gen.address   of BinaryOpNode.low..BinaryOpNode.high: gen.process(node.left) gen.process(node.right) gen.genSimpleInst(BinOp[node.kind]) inc gen.address   of PrintNode.low..PrintNode.high: gen.process(node.left) gen.genSimpleInst(PrintOp[node.kind]) inc gen.address   of nIf: # Generate condition expression. gen.process(node.left) # Generate jump if zero. let jzAddr = gen.address let jzInst = gen.genJumpInst(opJz) inc gen.address, 5 # Generate then branch expression. gen.process(node.right.left) # If there is an "else" clause, generate unconditional jump var jmpAddr, jmpInst: int let hasElseClause = not node.right.right.isNil if hasElseClause: jmpAddr = gen.address jmpInst = gen.genJumpInst(opJmp) inc gen.address, 5 # Update JZ offset. gen.updateJumpInst(jzInst, jzAddr, gen.address) # Generate else expression. if hasElseClause: gen.process(node.right.right) # Update JMP offset. gen.updateJumpInst(jmpInst, jmpAddr, gen.address)   of nWhile: let condAddr = gen.address # Generate condition expression. gen.process(node.left) # Generate jump if zero. let jzAddr = gen.address let jzInst = gen.genJumpInst(opJz) inc gen.address, 5 # Generate loop code. gen.process(node.right) # Generate unconditional jump. let jmpAddr = gen.address let jmpInst = gen.genJumpInst(opJmp) inc gen.address, 5 # Update JMP offset. gen.updateJumpInst(jmpInst, jmpAddr, condAddr) # Update JZ offset. gen.updateJumpInst(jzInst, jzAddr, gen.address)   of nSequence: gen.process(node.left) gen.process(node.right)   #---------------------------------------------------------------------------------------------------   proc run(gen: var CodeGen; ast: Node) = ## Run the code generator on the AST.   # Process recursively the nodes. gen.process(ast) gen.genSimpleInst(opHalt) # Add a Halt operator at the end.   # Output header. echo &"Datasize: {gen.vars.len} Strings: {gen.strings.len}" # Output strings. for s in gen.strings: echo s.escape().replace("\\x0A", "\\n") # Output code. for inst in gen.instr: echo inst   #################################################################################################### # AST loader.   proc newNode(kind: NodeKind; left: Node; right: Node = nil): Node = ## Create a new node with given left and right children. result = Node(kind: kind, left: left, right: right)   #---------------------------------------------------------------------------------------------------   proc loadAst(stream: Stream): Node = ## Load a linear AST and build a binary tree.   let line = stream.readLine().strip() if line.startsWith(';'): return nil   var fields = line.split(' ', 1) let kind = parseEnum[NodeKind](fields[0]) if kind in {nIdentifier, nString, nInteger}: if fields.len < 2: raise newException(ValueError, "Missing value field for " & fields[0]) else: fields[1] = fields[1].strip() case kind of nIdentifier: return Node(kind: nIdentifier, name: fields[1]) of nString: let str = fields[1].replacef(re"([^\\])(\\n)", "$1\n").replace(r"\\", r"\").replace("\"", "") return Node(kind: nString, stringVal: str) of nInteger: return Node(kind: nInteger, intVal: parseInt(fields[1])) else: if fields.len > 1: raise newException(ValueError, "Extra field for " & fields[0])   let left = stream.loadAst() let right = stream.loadAst() result = newNode(kind, left, right)     #———————————————————————————————————————————————————————————————————————————————————————————————————   var stream: Stream var toClose = false var codegen: CodeGen   if paramCount() < 1: stream = newFileStream(stdin) else: stream = newFileStream(paramStr(1)) toClose = true   let ast = loadAst(stream) if toClose: stream.close()   codegen.run(ast)
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Measure a relative performance of sorting algorithms implementations. Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures). Consider three type of input sequences:   ones: sequence of all 1's.   Example: {1, 1, 1, 1, 1}   range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}   shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8} Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm). For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations. Preliminary subtask:   Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort   Query Performance   Write float arrays to a text file   Plot x, y arrays   Polynomial Fitting General steps:   Define sorting routines to be considered.   Define appropriate sequence generators and write timings.   Plot timings.   What conclusions about relative performance of the sorting routines could be made based on the plots?
#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 end ary = buckets.flatten end ary end   def quick_sort return self if size <= 1 pivot = sample g = group_by{|x| x<=>pivot} g.default = [] g[-1].quick_sort + g[0] + g[1].quick_sort end   def shell_sort inc = size / 2 while inc > 0 (inc...size).each do |i| value = self[i] while i >= inc and self[i - inc] > value self[i] = self[i - inc] i -= inc end self[i] = value end inc = (inc == 2 ? 1 : (inc * 5.0 / 11).to_i) end self end   def insertion_sort (1...size).each do |i| value = self[i] j = i - 1 while j >= 0 and self[j] > value self[j+1] = self[j] j -= 1 end self[j+1] = value end self end   def bubble_sort (1...size).each do |i| (0...size-i).each do |j| self[j], self[j+1] = self[j+1], self[j] if self[j] > self[j+1] end end self end end   data_size = [1000, 10000, 100000, 1000000] data = [] data_size.each do |size| ary = *1..size data << [ [1]*size, ary, ary.shuffle, ary.reverse ] end data = data.transpose   data_type = ["set to all ones", "ascending sequence", "randomly shuffled", "descending sequence"] print "Array size: " puts data_size.map{|size| "%9d" % size}.join   data.each_with_index do |arys,i| puts "\nData #{data_type[i]}:" [:sort, :radix_sort, :quick_sort, :shell_sort, :insertion_sort, :bubble_sort].each do |m| printf "%20s ", m flag = true arys.each do |ary| if flag t0 = Time.now ary.dup.send(m) printf "  %7.3f", (t1 = Time.now - t0) flag = false if t1 > 2 else print " --.---" end end puts end end
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 | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a parser module/library/class, it would be great if two versions of the solution are provided: One without the parser module, and one with. Grammar The simple programming language to be analyzed is more or less a (very tiny) subset of C. The formal grammar in Extended Backus-Naur Form (EBNF):   stmt_list = {stmt} ;   stmt = ';' | Identifier '=' expr ';' | 'while' paren_expr stmt | 'if' paren_expr stmt ['else' stmt] | 'print' '(' prt_list ')' ';' | 'putc' paren_expr ';' | '{' stmt_list '}'  ;   paren_expr = '(' expr ')' ;   prt_list = (string | expr) {',' (String | expr)} ;   expr = and_expr {'||' and_expr} ; and_expr = equality_expr {'&&' equality_expr} ; equality_expr = relational_expr [('==' | '!=') relational_expr] ; relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ; addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ; multiplication_expr = primary {('*' | '/' | '%') primary } ; primary = Identifier | Integer | '(' expr ')' | ('+' | '-' | '!') primary  ; The resulting AST should be formulated as a Binary Tree. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast The following table shows the input to lex, lex output, and the AST produced by the parser Input to lex Output from lex, input to parse Output from parse count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Specifications List of node type names Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or In the text below, Null/Empty nodes are represented by ";". Non-terminal (internal) nodes For Operators, the following nodes should be created: Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or For each of the above nodes, the left and right sub-nodes are the operands of the respective operation. In pseudo S-Expression format: (Operator expression expression) Negate, Not For these node types, the left node is the operand, and the right node is null. (Operator expression ;) Sequence - sub-nodes are either statements or Sequences. If - left node is the expression, the right node is If node, with it's left node being the if-true statement part, and the right node being the if-false (else) statement part. (If expression (If statement else-statement)) If there is not an else, the tree becomes: (If expression (If statement ;)) Prtc (Prtc (expression) ;) Prts (Prts (String "the string") ;) Prti (Prti (Integer 12345) ;) While - left node is the expression, the right node is the statement. (While expression statement) Assign - left node is the left-hand side of the assignment, the right node is the right-hand side of the assignment. (Assign Identifier expression) Terminal (leaf) nodes: Identifier: (Identifier ident_name) Integer: (Integer 12345) String: (String "Hello World!") ";": Empty node Some simple examples Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path. This simple program: a=11; Produces the following AST, encoded as a binary tree: Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node: (1) Sequence (2) |-- ; (3) |-- Assign (4) |-- Identifier: a (5) |-- Integer: 11 In flattened form: (1) Sequence (2) ; (3) Assign (4) Identifier a (5) Integer 11 This program: a=11; b=22; c=33; Produces the following AST: ( 1) Sequence ( 2) |-- Sequence ( 3) | |-- Sequence ( 4) | | |-- ; ( 5) | | |-- Assign ( 6) | | |-- Identifier: a ( 7) | | |-- Integer: 11 ( 8) | |-- Assign ( 9) | |-- Identifier: b (10) | |-- Integer: 22 (11) |-- Assign (12) |-- Identifier: c (13) |-- Integer: 33 In flattened form: ( 1) Sequence ( 2) Sequence ( 3) Sequence ( 4) ; ( 5) Assign ( 6) Identifier a ( 7) Integer 11 ( 8) Assign ( 9) Identifier b (10) Integer 22 (11) Assign (12) Identifier c (13) Integer 33 Pseudo-code for the parser. Uses Precedence Climbing for expression parsing, and Recursive Descent for statement parsing. The AST is also built: def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error()   while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q))   return x   def paren_expr() expect("(") x = expr(0) expect(")") return x   def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0))   t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t   def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t Once the AST is built, it should be output in a flattened format. This can be as simple as the following def prt_ast(t) if t == NULL print(";\n") else print(t.node_type) if t.node_type in [Identifier, Integer, String] # leaf node print the value of the Ident, Integer or String, "\n" else print("\n") prt_ast(t.left) prt_ast(t.right) If the AST is correctly built, loading it into a subsequent program should be as simple as def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) Finally, the AST can also be tested by running it against one of the AST Interpreter solutions. Test program, assuming this is in a file called prime.t lex <prime.t | parse Input to lex Output from lex, input to parse Output from parse /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 4 1 Identifier count 4 7 Op_assign 4 9 Integer 1 4 10 Semicolon 5 1 Identifier n 5 3 Op_assign 5 5 Integer 1 5 6 Semicolon 6 1 Identifier limit 6 7 Op_assign 6 9 Integer 100 6 12 Semicolon 7 1 Keyword_while 7 7 LeftParen 7 8 Identifier n 7 10 Op_less 7 12 Identifier limit 7 17 RightParen 7 19 LeftBrace 8 5 Identifier k 8 6 Op_assign 8 7 Integer 3 8 8 Semicolon 9 5 Identifier p 9 6 Op_assign 9 7 Integer 1 9 8 Semicolon 10 5 Identifier n 10 6 Op_assign 10 7 Identifier n 10 8 Op_add 10 9 Integer 2 10 10 Semicolon 11 5 Keyword_while 11 11 LeftParen 11 12 LeftParen 11 13 Identifier k 11 14 Op_multiply 11 15 Identifier k 11 16 Op_lessequal 11 18 Identifier n 11 19 RightParen 11 21 Op_and 11 24 LeftParen 11 25 Identifier p 11 26 RightParen 11 27 RightParen 11 29 LeftBrace 12 9 Identifier p 12 10 Op_assign 12 11 Identifier n 12 12 Op_divide 12 13 Identifier k 12 14 Op_multiply 12 15 Identifier k 12 16 Op_notequal 12 18 Identifier n 12 19 Semicolon 13 9 Identifier k 13 10 Op_assign 13 11 Identifier k 13 12 Op_add 13 13 Integer 2 13 14 Semicolon 14 5 RightBrace 15 5 Keyword_if 15 8 LeftParen 15 9 Identifier p 15 10 RightParen 15 12 LeftBrace 16 9 Keyword_print 16 14 LeftParen 16 15 Identifier n 16 16 Comma 16 18 String " is prime\n" 16 31 RightParen 16 32 Semicolon 17 9 Identifier count 17 15 Op_assign 17 17 Identifier count 17 23 Op_add 17 25 Integer 1 17 26 Semicolon 18 5 RightBrace 19 1 RightBrace 20 1 Keyword_print 20 6 LeftParen 20 7 String "Total primes found: " 20 29 Comma 20 31 Identifier count 20 36 Comma 20 38 String "\n" 20 42 RightParen 20 43 Semicolon 21 1 End_of_input Sequence Sequence Sequence Sequence Sequence ; Assign Identifier count Integer 1 Assign Identifier n Integer 1 Assign Identifier limit Integer 100 While Less Identifier n Identifier limit Sequence Sequence Sequence Sequence Sequence ; Assign Identifier k Integer 3 Assign Identifier p Integer 1 Assign Identifier n Add Identifier n Integer 2 While And LessEqual Multiply Identifier k Identifier k Identifier n Identifier p Sequence Sequence ; Assign Identifier p NotEqual Multiply Divide Identifier n Identifier k Identifier k Identifier n Assign Identifier k Add Identifier k Integer 2 If Identifier p If Sequence Sequence ; Sequence Sequence ; Prti Identifier n ; Prts String " is prime\n" ; Assign Identifier count Add Identifier count Integer 1 ; Sequence Sequence Sequence ; Prts String "Total primes found: " ; Prti Identifier count ; Prts String "\n" ; Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#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 traversal. The # mutually recursive parser itself is more difficult to handle; for # that, I implement a tiny, FORTH-like token processor that supports # recursive calls. # # How to deal with input is another problem. I use formatted input, # treating each line as a (regrettably fixed length) array of type # CHARACTER. It is a very simple method, and leaves the input in a # form convenient for the necessary processing (given that the input # is not formatted in columns). # # # On a POSIX platform, the program can be compiled with f2c and run # somewhat as follows: # # ratfor77 parse-in-ratfor.r > parse-in-ratfor.f # f2c -C -Nc40 parse-in-ratfor.f # cc parse-in-ratfor.c -lf2c # ./a.out < compiler-tests/primes.lex # # With gfortran, a little differently: # # ratfor77 parse-in-ratfor.r > parse-in-ratfor.f # gfortran -fcheck=all -std=legacy parse-in-ratfor.f # ./a.out < compiler-tests/primes.lex # # # I/O is strictly from default input and to default output, which, on # POSIX systems, usually correspond respectively to standard input and # standard output. # #---------------------------------------------------------------------   # Parameters that you can adjust.   define(LINESZ, 256) # Size of an input line. define(STRNSZ, 4096) # Size of the string pool. define(NODSSZ, 4096) # Size of the nodes pool. define(DSTKSZ, 4096) # Size of the data stack. define(PSTKSZ, 4096) # Size of the precedence stack. define(XSTKSZ, 4096) # Size of the execution stack.   #---------------------------------------------------------------------   define(TOKSZ, 5) # Size of a lexical token, in integers. define(ILN, 1) # Index for line number. define(ICN, 2) # Index for column number. define(ITK, 3) # Index for token number. define(ITV, 4) # Index for the string pool index of the token value. define(ITN, 5) # Index for the length of the token value.   define(NODESZ, 3) define(NTAG, 1) # Index for the tag. # For an internal node -- define(NLEFT, 2) # Index for the left node. define(NRIGHT, 3) # Index for the right node. # For a leaf node -- define(NITV, 2) # Index for the string pool index. define(NITN, 3) # Length of the value.   define(NIL, -1) # Nil node.   define(TKELSE, 0) define(TKIF, 1) define(TKPRNT, 2) define(TKPUTC, 3) define(TKWHIL, 4) define(TKMUL, 5) define(TKDIV, 6) define(TKMOD, 7) define(TKADD, 8) define(TKSUB, 9) define(TKNEG, 10) define(TKLT, 11) define(TKLE, 12) define(TKGT, 13) define(TKGE, 14) define(TKEQ, 15) define(TKNE, 16) define(TKNOT, 17) define(TKASGN, 18) define(TKAND, 19) define(TKOR, 20) define(TKLPAR, 21) define(TKRPAR, 22) define(TKLBRC, 23) define(TKRBRC, 24) define(TKSEMI, 25) define(TKCMMA, 26) define(TKID, 27) define(TKINT, 28) define(TKSTR, 29) define(TKEOI, 30)   define(NDID, 0) define(NDSTR, 1) define(NDINT, 2) define(NDSEQ, 3) define(NDIF, 4) define(NDPRTC, 5) define(NDPRTS, 6) define(NDPRTI, 7) define(NDWHIL, 8) define(NDASGN, 9) define(NDNEG, 10) define(NDNOT, 11) define(NDMUL, 12) define(NDDIV, 13) define(NDMOD, 14) define(NDADD, 15) define(NDSUB, 16) define(NDLT, 17) define(NDLE, 18) define(NDGT, 19) define(NDGE, 20) define(NDEQ, 21) define(NDNE, 22) define(NDAND, 23) define(NDOR, 24)   subroutine string (src, isrc, nsrc, strngs, istrng, i, n)   # Store a string in the string pool.   implicit none   character src(*) # Source string. integer isrc, nsrc # Index and length of the source substring. character strngs(STRNSZ) # The string pool. integer istrng # The string pool's next slot. integer i, n # Index and length within the string pool.   integer j   if (STRNSZ < istrng + nsrc) { write (*, '(''string pool exhausted'')') stop } for (j = 0; j < nsrc; j = j + 1) strngs(istrng + j) = src(isrc + j) i = istrng n = nsrc istrng = istrng + nsrc end   subroutine astnod (node, nodes, inodes, i)   # Store a node in the nodes pool.   implicit none   integer node(NODESZ) integer nodes(NODESZ, NODSSZ) integer inodes integer i   integer j   if (NODSSZ < inodes + 1) { write (*, '(''node pool exhausted'')') stop } i = inodes inodes = inodes + 1 for (j = 1; j <= NODESZ; j = j + 1) nodes(j, i) = node(j) end   function issp (c)   # Is a character a space character?   implicit none   character c logical issp   integer ic   ic = ichar (c) issp = (ic == 32 || (9 <= ic && ic <= 13)) end   function skipsp (str, i, imax)   # Skip past spaces in a string.   implicit none   character str(*) integer i integer imax integer skipsp   logical issp   logical done   skipsp = i done = .false. while (!done) { if (imax <= skipsp) done = .true. else if (!issp (str(skipsp))) done = .true. else skipsp = skipsp + 1 } end   function skipns (str, i, imax)   # Skip past non-spaces in a string.   implicit none   character str(*) integer i integer imax integer skipns   logical issp   logical done   skipns = i done = .false. while (!done) { if (imax <= skipns) done = .true. else if (issp (str(skipns))) done = .true. else skipns = skipns + 1 } end   function trimrt (str, n)   # Find the length of a string, if one ignores trailing spaces.   implicit none   character str(*) integer n integer trimrt   logical issp   logical done   trimrt = n done = .false. while (!done) { if (trimrt == 0) done = .true. else if (!issp (str(trimrt))) done = .true. else trimrt = trimrt - 1 } end   function mktok (str, i, n)   # Convert a substring to a token integer.   implicit none   character str(*) integer i integer n integer mktok   character*16 tokstr(0:30) character*16 test integer j logical done   data tokstr / 'Keyword_else ', _ 'Keyword_if ', _ 'Keyword_print ', _ 'Keyword_putc ', _ 'Keyword_while ', _ 'Op_multiply ', _ 'Op_divide ', _ 'Op_mod ', _ 'Op_add ', _ 'Op_subtract ', _ 'Op_negate ', _ 'Op_less ', _ 'Op_lessequal ', _ 'Op_greater ', _ 'Op_greaterequal ', _ 'Op_equal ', _ 'Op_notequal ', _ 'Op_not ', _ 'Op_assign ', _ 'Op_and ', _ 'Op_or ', _ 'LeftParen ', _ 'RightParen ', _ 'LeftBrace ', _ 'RightBrace ', _ 'Semicolon ', _ 'Comma ', _ 'Identifier ', _ 'Integer ', _ 'String ', _ 'End_of_input ' /   test = ' ' for (j = 0; j < n; j = j + 1) test(j + 1 : j + 1) = str(i + j)   j = 0 done = .false. while (!done) { if (TKEOI < j) { write (*, '(''unrecognized token'')') stop } else if (test == tokstr(j)) done = .true. else j = j + 1 }   mktok = j end   function mkint (str, i, n)   # Convert a unsigned integer substring to an integer.   implicit none   character str(*) integer i integer n integer mkint   integer j   mkint = 0 for (j = 0; j < n; j = j + 1) mkint = (10 * mkint) + (ichar (str(i + j)) - 48) end   subroutine rdtok (strngs, istrng, blank, linno, colno, tokno, _ itkval, ntkval)   # Read a token from the input.   implicit none   character strngs(STRNSZ) # The string pool. integer istrng # The string pool's next slot. logical blank # Is the line blank? integer linno # The line number. integer colno # The column number. integer tokno # The token number. integer itkval, ntkval # Token value as a string.   integer skipsp, skipns, trimrt integer mkint, mktok   character line(LINESZ) character*20 fmt integer n, i, j   # Read a line of text as an array of characters. write (fmt, '(''('', I10, ''A1)'')') LINESZ read (*, fmt) line   n = trimrt (line, LINESZ) blank = (n == 0)   if (!blank) { i = skipsp (line, 1, n + 1) j = skipns (line, i, n + 1) linno = mkint (line, i, j - i)   i = skipsp (line, j, n + 1) j = skipns (line, i, n + 1) colno = mkint (line, i, j - i)   i = skipsp (line, j, n + 1) j = skipns (line, i, n + 1) tokno = mktok (line, i, j - i)   i = skipsp (line, j, n + 1) j = n + 1 call string (line, i, j - i, strngs, istrng, itkval, ntkval) } end   subroutine gettok (strngs, istrng, tok)   # Get the next token.   implicit none   character strngs(STRNSZ) # The string pool. integer istrng # The string pool's next slot. integer tok(TOKSZ)   integer linno, colno, tokno, itkval, ntkval logical blank   blank = .true. while (blank) call rdtok (strngs, istrng, blank, linno, colno, tokno, _ itkval, ntkval) tok(ILN) = linno tok(ICN) = colno tok(ITK) = tokno tok(ITV) = itkval tok(ITN) = ntkval end   function accept (strngs, istrng, curtok, tokno)   implicit none   character strngs(STRNSZ) # The string pool. integer istrng # The string pool's next slot. integer curtok(TOKSZ) integer tokno logical accept   accept = (curtok(ITK) == tokno) if (accept) call gettok (strngs, istrng, curtok) end   subroutine expect (strngs, istrng, curtok, tokno)   implicit none   character strngs(STRNSZ) # The string pool. integer istrng # The string pool's next slot. integer curtok(TOKSZ) integer tokno   logical accept   if (!accept (strngs, istrng, curtok, tokno)) { # This is not the same message as printed by the reference C # implementation. You can change that, if you wish. write (*, 100) curtok(ILN), curtok(ICN) 100 format ('unexpected token at line ', I5, ', column ', I5) stop } end   function prec (tokno)   # Precedence.   implicit none   integer tokno integer prec   if (tokno == TKMUL || tokno == TKDIV || tokno == TKMOD) prec = 13 else if (tokno == TKADD || tokno == TKSUB) prec = 12 else if (tokno == TKNEG || tokno == TKNOT) prec = 14 else if (tokno == TKLT || tokno == TKLE || _ tokno == TKGT || tokno == TKGE) prec = 10 else if (tokno == TKEQ || tokno == TKNE) prec = 9 else if (tokno == TKAND) prec = 5 else if (tokno == TKOR) prec = 4 else prec = -1 end   function isbin (tokno)   # Is an operation binary?   implicit none   integer tokno logical isbin   isbin = (tokno == TKADD || _ tokno == TKSUB || _ tokno == TKMUL || _ tokno == TKDIV || _ tokno == TKMOD || _ tokno == TKLT || _ tokno == TKLE || _ tokno == TKGT || _ tokno == TKGE || _ tokno == TKEQ || _ tokno == TKNE || _ tokno == TKAND || _ tokno == TKOR) end   function rtassc (tokno)   # Is an operation right associative?   implicit none   integer tokno logical rtassc   # None of the current operators is right associative. rtassc = .false. end   function opernt (tokno)   # Return the node tag for a binary operator.   implicit none   integer tokno integer opernt   if (tokno == TKMUL) opernt = NDMUL else if (tokno == TKDIV) opernt = NDDIV else if (tokno == TKMOD) opernt = NDMOD else if (tokno == TKADD) opernt = NDADD else if (tokno == TKSUB) opernt = NDSUB else if (tokno == TKNEG) opernt = NDNEG else if (tokno == TKNOT) opernt = NDNOT else if (tokno == TKLT) opernt = NDLT else if (tokno == TKLE) opernt = NDLE else if (tokno == TKGT) opernt = NDGT else if (tokno == TKGE) opernt = NDGE else if (tokno == TKEQ) opernt = NDEQ else if (tokno == TKNE) opernt = NDNE else if (tokno == TKAND) opernt = NDAND else if (tokno == TKOR) opernt = NDOR else { write (*, '(''unrecognized binary operator'')') stop } end   #---------------------------------------------------------------------   subroutine prtast (strngs, nodes, i, dstack)   # Print a tree in flattened format.   implicit none   character strngs(*) integer nodes(NODESZ, NODSSZ) integer i integer dstack(DSTKSZ)   integer j integer k integer n integer q, r integer tag   character*80 fmt   dstack(1) = i j = 2 while (j != 1) { j = j - 1 k = dstack(j) if (k < 1) write (*, '('';'')') else { tag = nodes(NTAG, k) if (tag == NDID) { n = nodes(NITN, k) write (fmt, '(''("Identifier ", '', I5, ''A)'')') n q = nodes(NITV, k) write (*, fmt) (strngs(r), r = q, q + n - 1) } else if (tag == NDINT) { n = nodes(NITN, k) write (fmt, '(''("Integer ", '', I5, ''A)'')') n q = nodes(NITV, k) write (*, fmt) (strngs(r), r = q, q + n - 1) } else if (tag == NDSTR) { n = nodes(NITN, k) write (fmt, '(''("String ", '', I5, ''A)'')') n q = nodes(NITV, k) write (*, fmt) (strngs(r), r = q, q + n - 1) } else { if (tag == NDSEQ) write (*, '(''Sequence'')') else if (tag == NDIF) write (*, '(''If'')') else if (tag == NDPRTC) write (*, '(''Prtc'')') else if (tag == NDPRTS) write (*, '(''Prts'')') else if (tag == NDPRTI) write (*, '(''Prti'')') else if (tag == NDWHIL) write (*, '(''While'')') else if (tag == NDASGN) write (*, '(''Assign'')') else if (tag == NDNEG) write (*, '(''Negate'')') else if (tag == NDNOT) write (*, '(''Not'')') else if (tag == NDMUL) write (*, '(''Multiply'')') else if (tag == NDDIV) write (*, '(''Divide'')') else if (tag == NDMOD) write (*, '(''Mod'')') else if (tag == NDADD) write (*, '(''Add'')') else if (tag == NDSUB) write (*, '(''Subtract'')') else if (tag == NDLT) write (*, '(''Less'')') else if (tag == NDLE) write (*, '(''LessEqual'')') else if (tag == NDGT) write (*, '(''Greater'')') else if (tag == NDGE) write (*, '(''GreaterEqual'')') else if (tag == NDEQ) write (*, '(''Equal'')') else if (tag == NDNE) write (*, '(''NotEqual'')') else if (tag == NDAND) write (*, '(''And'')') else if (tag == NDOR) write (*, '(''Or'')') else { write (*, '(''unrecognized node type'')') stop } if (DSTKSZ - 2 < n) { write (*, '(''node stack overflow'')') stop } dstack(j) = nodes(NRIGHT, k) dstack(j + 1) = nodes(NLEFT, k) j = j + 2 } } } end   #---------------------------------------------------------------------   # A tiny recursive language. Each instruction is two integers, # although the second integer may be XPAD. XLOCs are named by # integers.   define(XPAD, 0) # "Padding"   define(XLOC, 10) # "Jump or call location" define(XJUMP, 20) # "Jump to a place" define(XJUMPT, 30) # "Jump to a place, if true" define(XJUMPF, 40) # "Jump to a place, if false" define(XCALL, 50) # "Call a subprogram" define(XRET, 60) # "Return from a subprogram"   define(XPUSH, 110) # "Push an immediate value" define(XSWAP, 120) # "Swap top two stack entries"   define(XLT, 200) # "Less than?" define(XADDI, 210) # "Add immediate."   define(XPPUSH, 610) # "Push top to precedence stack" define(XPCOPY, 620) # "Copy top of prec stack to top" define(XPDROP, 630) # "Drop top of precedence stack"   define(XGETTK, 710) # "Get the next token" define(XTOKEQ, 720) # "Token equals the argument?" define(XEXPCT, 730) # "Expect token" define(XACCPT, 740) # "Accept token"   define(XTOK, 810) # "Push the token number" define(XBINOP, 820) # "Is top a binary operator?" define(XRASSC, 830) # "Is top a right associative op?" define(XPREC, 840) # "Precedence of token no. on top" define(XOPER, 850) # "Operator for token no. on top"   define(XINTND, 970) # "Make internal node" define(XOPND, 975) # "Make internal node for operator" define(XLEFND, 980) # "Make leaf node" define(XNILND, 985) # "Make nil node"   define(XERROR, 1010) # "Error" define(XRWARN, 1020) # "Unused right associative branch"   define(XPING, 2010) # Print a ping message (for debugging) define(XPRTND, 2020) # Print node at stack top (for debugging) define(XPRTTP, 2030) # Print stack top as integer (for debugging) define(XPRTTK, 2040) # Print the current token (for debugging) define(XPRTP, 2050) # Print the current precedence (for debugging) define(XPRTST, 2060) # Print the whole data stack (for debugging)   # Call and jump locations in our program: define(CSTMT, 1000) # stmt define(STMT01, 1010) define(STMT02, 1020) define(STMT03, 1030) define(STMT04, 1040) define(STMT05, 1050) define(STMT06, 1060) define(STMT07, 1070) define(STMT08, 1080) define(STMT09, 1090) define(STMT10, 1100) define(STMT11, 1110) define(STMT12, 1120) define(STMT13, 1130) define(STMT14, 1140) define(STMT15, 1150) define(CPEXPR, 2000) # paren_expr define(CEXPR, 3000) # expr define(EXPR01, 3010) define(EXPR02, 3020) define(EXPR03, 3030) define(EXPR04, 3040) define(EXPR05, 3050) define(EXPR06, 3060) define(EXPR10, 3100) define(EXPR11, 3110) define(EXPR12, 3120) define(EXPR13, 3130) define(PARS01, 4010) # parse   # Error numbers. define(EXSTMT, 100) # "expecting start of statement" define(EXPRIM, 200) # "expecting a primary"   # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   subroutine ld(code, i, instr1, instr2)   implicit none   integer code(*) integer i integer instr1, instr2   code(i) = instr1 code(i + 1) = instr2 i = i + 2 end   subroutine ldcode (code)   # Load the code that is in the recursive language. The array # allocated to hold the code must be large enough, but we do not # check.   implicit none   integer code(*) integer i   i = 1   #--------------------------------------------------   # The main loop. call ld (code, i, XNILND, XPAD) # Nil node for start of sequence. call ld (code, i, XGETTK, XPAD) call ld (code, i, XLOC, PARS01) # Top of loop call ld (code, i, XCALL, CSTMT) call ld (code, i, XINTND, NDSEQ) call ld (code, i, XTOKEQ, TKEOI) # End_of_input call ld (code, i, XJUMPF, PARS01) # Loop unless end of input. call ld (code, i, XRET, XPAD)   #--------------------------------------------------   call ld (code, i, XLOC, CEXPR) # Start of "expr" call ld (code, i, XPPUSH, XPAD) # Push the precedence argument.   call ld (code, i, XTOKEQ, TKLPAR) # LeftParen call ld (code, i, XJUMPF, EXPR01)   # "( ... )" call ld (code, i, XCALL, CPEXPR) call ld (code, i, XJUMP, EXPR10)   call ld (code, i, XLOC, EXPR01)   call ld (code, i, XACCPT, TKSUB) # Op_subtract call ld (code, i, XJUMPF, EXPR02)   # Unary minus call ld (code, i, XPUSH, TKNEG) call ld (code, i, XPREC, XPAD) call ld (code, i, XCALL, CEXPR) # expr <-- call ld (code, i, XNILND, XPAD) # expr nil <-- call ld (code, i, XINTND, NDNEG) call ld (code, i, XJUMP, EXPR10)   call ld (code, i, XLOC, EXPR02)   call ld (code, i, XACCPT, TKADD) # Op_add call ld (code, i, XJUMPF, EXPR03)   # Unary plus call ld (code, i, XPUSH, TKNEG) call ld (code, i, XPREC, XPAD) call ld (code, i, XCALL, CEXPR) # expr <-- call ld (code, i, XJUMP, EXPR10)   call ld (code, i, XLOC, EXPR03)   call ld (code, i, XACCPT, TKNOT) # Op_not call ld (code, i, XJUMPF, EXPR04)   # "!" call ld (code, i, XPUSH, TKNOT) call ld (code, i, XPREC, XPAD) call ld (code, i, XCALL, CEXPR) # expr <-- call ld (code, i, XNILND, XPAD) # expr nil <-- call ld (code, i, XINTND, NDNOT) call ld (code, i, XJUMP, EXPR10)   call ld (code, i, XLOC, EXPR04)   call ld (code, i, XTOKEQ, TKID) # Identifier call ld (code, i, XJUMPF, EXPR05)   # Identifier call ld (code, i, XLEFND, NDID) call ld (code, i, XGETTK, XPAD) call ld (code, i, XJUMP, EXPR10)   call ld (code, i, XLOC, EXPR05)   call ld (code, i, XTOKEQ, TKINT) # Integer call ld (code, i, XJUMPF, EXPR06)   # Integer. call ld (code, i, XLEFND, NDINT) call ld (code, i, XGETTK, XPAD) call ld (code, i, XJUMP, EXPR10)   call ld (code, i, XLOC, EXPR06)   call ld (code, i, XERROR, EXPRIM)   call ld (code, i, XLOC, EXPR10) # Top of precedence climbing loop   call ld (code, i, XTOK, XPAD) call ld (code, i, XBINOP, XPAD) call ld (code, i, XJUMPF, EXPR11) # Exit loop, if not a binary op.   call ld (code, i, XTOK, XPAD) call ld (code, i, XPREC, XPAD) # curtok_prec <-- call ld (code, i, XPCOPY, XPAD) # curtok_prec p <-- call ld (code, i, XLT, XPAD) # (curtok_prec < p)? <-- call ld (code, i, XJUMPT, EXPR11) # Exit loop if true.   call ld (code, i, XTOK, XPAD) call ld (code, i, XOPER, XPAD) # x op <-- call ld (code, i, XSWAP, XPAD) # op x <--   call ld (code, i, XTOK, XPAD) call ld (code, i, XRASSC, XPAD) call ld (code, i, XJUMPT, EXPR12)   # Left associative. call ld (code, i, XTOK, XPAD) call ld (code, i, XPREC, XPAD) call ld (code, i, XADDI, 1) # op x q:=(q + 1) <-- call ld (code, i, XJUMP, EXPR13)   call ld (code, i, XLOC, EXPR12)   # Right associative. (Currently an unused branch.) call ld (code, i, XRWARN, XPAD) # Warn about unused branch. call ld (code, i, XTOK, XPAD) call ld (code, i, XPREC, XPAD) # op x q <--   call ld (code, i, XLOC, EXPR13)   call ld (code, i, XGETTK, XPAD) call ld (code, i, XCALL, CEXPR) # op x expr(q) <-- call ld (code, i, XOPND, XPAD) # new_x <--   call ld (code, i, XJUMP, EXPR10) # Continue looping.   call ld (code, i, XLOC, EXPR11) # Loop exit.   call ld (code, i, XPDROP, XPAD) # Drop the precedence argument. call ld (code, i, XRET, XPAD) # End of "expr"   #--------------------------------------------------   call ld (code, i, XLOC, CPEXPR) # Start of "paren_expr" call ld (code, i, XEXPCT, TKLPAR) call ld (code, i, XPUSH, 0) call ld (code, i, XCALL, CEXPR) call ld (code, i, XEXPCT, TKRPAR) call ld (code, i, XRET, XPAD)   #--------------------------------------------------   call ld (code, i, XLOC, CSTMT) # Start of "stmt"   call ld (code, i, XACCPT, TKIF) # Keyword_if call ld (code, i, XJUMPF, STMT01)   # "if (...) then ... else ..." call ld (code, i, XCALL, CPEXPR) # Get the paren expr ("if (...)"). call ld (code, i, XCALL, CSTMT) # Get the "then" clause. call ld (code, i, XACCPT, TKELSE) # Keyword_else call ld (code, i, XJUMPF, STMT02) call ld (code, i, XCALL, CSTMT) # Get the "else" clause. call ld (code, i, XJUMP, STMT03) call ld (code, i, XLOC, STMT02) call ld (code, i, XNILND, XPAD) # The "else" statement is nil. call ld (code, i, XLOC, STMT03) call ld (code, i, XINTND, NDIF) # ("If" pred ("If" then else)) call ld (code, i, XINTND, NDIF) call ld (code, i, XRET, XPAD)   call ld (code, i, XLOC, STMT01)   call ld (code, i, XACCPT, TKPUTC) # Keyword_putc call ld (code, i, XJUMPF, STMT04)   # "putc (...);" call ld (code, i, XCALL, CPEXPR) # Get the paren expr. call ld (code, i, XNILND, XPAD) call ld (code, i, XINTND, NDPRTC) # ("Prtc" expr nil) call ld (code, i, XEXPCT, TKSEMI) # Expect ";" call ld (code, i, XRET, XPAD)   call ld (code, i, XLOC, STMT04)   call ld (code, i, XACCPT, TKPRNT) # Keyword_print call ld (code, i, XJUMPF, STMT05)   # "print(... , ... , ...);" call ld (code, i, XEXPCT, TKLPAR) # Expect "(" call ld (code, i, XNILND, XPAD) # nil for start of sequence call ld (code, i, XLOC, STMT08) # Top of loop call ld (code, i, XTOKEQ, TKSTR) call ld (code, i, XJUMPT, STMT06) call ld (code, i, XPUSH, 0) call ld (code, i, XCALL, CEXPR) call ld (code, i, XNILND, XPAD) call ld (code, i, XINTND, NDPRTI) # ("Prti" expr nil) call ld (code, i, XJUMP, STMT07) call ld (code, i, XLOC, STMT06) call ld (code, i, XLEFND, NDSTR) call ld (code, i, XNILND, XPAD) call ld (code, i, XINTND, NDPRTS) # ("Prts" ("String" ...) nil) call ld (code, i, XGETTK, XPAD) call ld (code, i, XLOC, STMT07) call ld (code, i, XINTND, NDSEQ) # ("Sequence" ... ...) call ld (code, i, XACCPT, TKCMMA) # Comma call ld (code, i, XJUMPT, STMT08) # Loop if comma. call ld (code, i, XEXPCT, TKRPAR) # Expect ")" call ld (code, i, XEXPCT, TKSEMI) # Expect ";" call ld (code, i, XRET, XPAD)   call ld (code, i, XLOC, STMT05)   call ld (code, i, XACCPT, TKSEMI) # Semicolon call ld (code, i, XJUMPF, STMT09)   # Accept a lone ";". call ld (code, i, XRET, XPAD)   call ld (code, i, XLOC, STMT09)   call ld (code, i, XTOKEQ, TKID) # Identifier call ld (code, i, XJUMPF, STMT10)   # "identifier = expr;" call ld (code, i, XLEFND, NDID) # ("Identifier" ...) call ld (code, i, XGETTK, XPAD) call ld (code, i, XEXPCT, TKASGN) call ld (code, i, XPUSH, 0) call ld (code, i, XCALL, CEXPR) call ld (code, i, XINTND, NDASGN) # ("Assign" ("Identifier" ...) expr) call ld (code, i, XEXPCT, TKSEMI) call ld (code, i, XRET, XPAD)   call ld (code, i, XLOC, STMT10)   call ld (code, i, XACCPT, TKWHIL) # While call ld (code, i, XJUMPF, STMT11)   # "while (...) ..." call ld (code, i, XCALL, CPEXPR) call ld (code, i, XCALL, CSTMT) call ld (code, i, XINTND, NDWHIL) # ("While" pred stmt) call ld (code, i, XRET, XPAD)   call ld (code, i, XLOC, STMT11)   call ld (code, i, XACCPT, TKLBRC) # LeftBrace call ld (code, i, XJUMPF, STMT12)   # "{ ... }" call ld (code, i, XNILND, XPAD) # nil for start of sequence call ld (code, i, XLOC, STMT13) # Top of loop call ld (code, i, XTOKEQ, TKEOI) call ld (code, i, XJUMPT, STMT14) call ld (code, i, XTOKEQ, TKRBRC) call ld (code, i, XJUMPT, STMT14) call ld (code, i, XCALL, CSTMT) call ld (code, i, XINTND, NDSEQ) # ("Sequence" ... ...) call ld (code, i, XJUMP, STMT13) # Loop again. call ld (code, i, XLOC, STMT14) # Loop exit call ld (code, i, XEXPCT, TKRBRC) # Expect ";". call ld (code, i, XRET, XPAD)   call ld (code, i, XLOC, STMT12)   call ld (code, i, XTOKEQ, TKEOI) # End_of_input call ld (code, i, XJUMPF, STMT15)   call ld (code, i, XRET, XPAD)   call ld (code, i, XLOC, STMT15)   call ld (code, i, XERROR, EXSTMT) # "expecting start of stmt"   #--------------------------------------------------   end   subroutine dtpush (dstack, idstck, x)   # Push to the data stack.   implicit none   integer dstack(DSTKSZ) integer idstck integer x   if (DSTKSZ < idstck) { write (*, '(''node stack exhausted'')') stop } dstack(idstck) = x idstck = idstck + 1 end   function dtpop (dstack, idstck)   # Pop from the data stack.   implicit none   integer dstack(DSTKSZ) integer idstck integer dtpop   if (DSTKSZ < idstck) { write (*, '(''node stack exhausted'')') stop } idstck = idstck - 1 dtpop = dstack(idstck) end   subroutine ppush (pstack, ipstck, x)   # Push to the precedence stack.   implicit none   integer pstack(PSTKSZ) integer ipstck integer x   if (PSTKSZ < ipstck) { write (*, '(''precedence stack exhausted'')') stop } pstack(ipstck) = x ipstck = ipstck + 1 end   function ppop (pstack, ipstck)   # Pop from the precedence stack.   implicit none   integer pstack(PSTKSZ) integer ipstck integer ppop   if (PSTKSZ < ipstck) { write (*, '(''precedence stack exhausted'')') stop } ipstck = ipstck - 1 ppop = pstack(ipstck) end   function ipfind (code, loc)   # Find a location.   implicit none   integer code(*) integer loc integer ipfind   integer i   i = 1 while (code(i) != XLOC || code(i + 1) != loc) i = i + 2 ipfind = i end   subroutine ippush (xstack, ixstck, ip)   # Push the instruction pointer.   implicit none   integer xstack(XSTKSZ) integer ixstck integer ip   if (XSTKSZ < ixstck) { write (*, '(''recursive call stack exhausted'')') stop } xstack(ixstck) = ip ixstck = ixstck + 1 end   function ippop (xstack, ixstck)   # Pop an instruction pointer value.   implicit none   integer xstack(XSTKSZ) integer ixstck integer ippop   if (ixstck == 1) { write (*, '(''recursive call stack underflow'')') stop } ixstck = ixstck - 1 ippop = xstack(ixstck) end   function logl2i (u)   # Convert LOGICAL to INTEGER.   implicit none   logical u integer logl2i   if (u) logl2i = 1 else logl2i = 0 end   subroutine recurs (strngs, istrng, nodes, inodes, _ dstack, idstck, _ pstack, ipstck, _ xstack, ixstck, _ code, ip)   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer nodes(NODESZ, NODSSZ) # Node pool integer inodes # Node pool's next slot. integer dstack(DSTKSZ) # Data stack. integer idstck # Data stack pointer. integer pstack(PSTKSZ) # Precedence stack. integer ipstck # Precedence stack pointer. integer xstack(XSTKSZ) # Execution stack. integer ixstck # Execution stack pointer. integer code(*) # Code in the recursive language. integer ip # Instruction pointer.   integer prec integer opernt integer logl2i integer dtpop integer ppop integer ippop integer ipfind logical accept logical isbin logical rtassc   integer curtok(TOKSZ) integer node(NODESZ) integer curprc # Current precedence value. integer i, j logical done   curprc = 0 done = .false. while (.not. done) { if (code(ip) == XLOC) { ip = ip + 2 } else if (code(ip) == XJUMP) { ip = ipfind (code, code(ip + 1)) } else if (code(ip) == XJUMPT) { i = dtpop (dstack, idstck) if (i != 0) ip = ipfind (code, code(ip + 1)) else ip = ip + 2 } else if (code(ip) == XJUMPF) { i = dtpop (dstack, idstck) if (i == 0) ip = ipfind (code, code(ip + 1)) else ip = ip + 2 } else if (code(ip) == XCALL) { call ippush (xstack, ixstck, ip + 2) ip = ipfind (code, code(ip + 1)) } else if (code(ip) == XRET) { if (ixstck == 1) done = .true. else ip = ippop (xstack, ixstck) } else if (code(ip) == XINTND) { node(NRIGHT) = dtpop (dstack, idstck) node(NLEFT) = dtpop (dstack, idstck) node(NTAG) = code(ip + 1) call astnod (node, nodes, inodes, i) call dtpush (dstack, idstck, i) ip = ip + 2 } else if (code(ip) == XOPND) { node(NRIGHT) = dtpop (dstack, idstck) node(NLEFT) = dtpop (dstack, idstck) node(NTAG) = dtpop (dstack, idstck) call astnod (node, nodes, inodes, i) call dtpush (dstack, idstck, i) ip = ip + 2 } else if (code(ip) == XLEFND) { node(NITV) = curtok(ITV) node(NITN) = curtok(ITN) node(NTAG) = code(ip + 1) call astnod (node, nodes, inodes, i) call dtpush (dstack, idstck, i) ip = ip + 2 } else if (code(ip) == XNILND) { call dtpush (dstack, idstck, NIL) ip = ip + 2 } else if (code(ip) == XGETTK) { call gettok (strngs, istrng, curtok) ip = ip + 2 } else if (code(ip) == XTOKEQ) { i = logl2i (curtok(ITK) == code(ip + 1)) call dtpush (dstack, idstck, i) ip = ip + 2 } else if (code(ip) == XEXPCT) { call expect (strngs, istrng, curtok, code(ip + 1)) ip = ip + 2 } else if (code(ip) == XACCPT) { i = logl2i (accept (strngs, istrng, curtok, code(ip + 1))) call dtpush (dstack, idstck, i) ip = ip + 2 } else if (code(ip) == XSWAP) { i = dtpop (dstack, idstck) j = dtpop (dstack, idstck) call dtpush (dstack, idstck, i) call dtpush (dstack, idstck, j) ip = ip + 2 } else if (code(ip) == XLT) { j = dtpop (dstack, idstck) i = dtpop (dstack, idstck) call dtpush (dstack, idstck, logl2i (i < j)) ip = ip + 2 } else if (code(ip) == XADDI) { i = dtpop (dstack, idstck) call dtpush (dstack, idstck, i + code(ip + 1)) ip = ip + 2 } else if (code(ip) == XPPUSH) { i = dtpop (dstack, idstck) call ppush (pstack, ipstck, i) ip = ip + 2 } else if (code(ip) == XPCOPY) { i = ppop (pstack, ipstck) call ppush (pstack, ipstck, i) call dtpush (dstack, idstck, i) ip = ip + 2 } else if (code(ip) == XPDROP) { i = ppop (pstack, ipstck) ip = ip + 2 } else if (code(ip) == XBINOP) { i = dtpop (dstack, idstck) i = logl2i (isbin (i)) call dtpush (dstack, idstck, i) ip = ip + 2 } else if (code(ip) == XRASSC) { i = dtpop (dstack, idstck) i = logl2i (rtassc (i)) call dtpush (dstack, idstck, i) ip = ip + 2 } else if (code(ip) == XPREC) { i = dtpop (dstack, idstck) call dtpush (dstack, idstck, prec (i)) ip = ip + 2 } else if (code(ip) == XOPER) { i = dtpop (dstack, idstck) call dtpush (dstack, idstck, opernt (i)) ip = ip + 2 } else if (code(ip) == XTOK) { call dtpush (dstack, idstck, curtok(ITK)) ip = ip + 2 } else if (code(ip) == XPUSH) { call dtpush (dstack, idstck, code(ip + 1)) ip = ip + 2 } else if (code(ip) == XERROR) { if (code(ip + 1) == EXSTMT) { write (*, 1000) curtok(ILN), curtok(ICN) 1000 format ('expected start of statement at line ', _ I5, ', column ', I5) } else if (code(ip + 1) == EXPRIM) { write (*, 1010) curtok(ILN), curtok(ICN) 1010 format ('expected a primary at line ', _ I5, ', column ', I5) } else { write (*, 2000) curtok(ILN), curtok(ICN) 2000 format ('syntax error at line ', _ I5, ', column ', I5) } stop } else if (code(ip) == XRWARN) { write (*, 3000) 3000 format ('executing supposedly unused ', _ '"right associative" operator branch') ip = ip + 2 } else if (code(ip) == XPING) { write (*, '(''ping'')') ip = ip + 2 } else if (code(ip) == XPRTND) { i = dtpop (dstack, idstck) call dtpush (dstack, idstck, i) call prtast (strngs, nodes, i, dstack) ip = ip + 2 } else if (code(ip) == XPRTTP) { i = dtpop (dstack, idstck) call dtpush (dstack, idstck, i) write (*, '(''top = '', I20)') i ip = ip + 2 } else if (code(ip) == XPRTTK) { write (*, '(''curtok ='', 5(1X, I5))') curtok ip = ip + 2 } else if (code(ip) == XPRTP) { write (*, '(''curprc = '', I2)') curprc ip = ip + 2 } else if (code(ip) == XPRTST) { write (*, '(''dstack ='', 100000(1X, I5))') _ (dstack(i), i = 1, idstck - 1) ip = ip + 2 } else { write (*, '(''illegal instruction'')') stop } } end   #---------------------------------------------------------------------   program parse   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer nodes(NODESZ, NODSSZ) # Node pool integer inodes # Node pool's next slot. integer dstack(DSTKSZ) # Node stack. integer idstck # Node stack pointer. integer pstack(PSTKSZ) # Precedence stack. integer ipstck # Precedence stack pointer. integer xstack(XSTKSZ) # Execution stack. integer ixstck # Execution stack pointer. integer code(1000) # Recursive code. integer ip # Instruction pointer.   integer i   integer dtpop   istrng = 1 inodes = 1 idstck = 1 ipstck = 1 ixstck = 1   call ldcode (code) ip = 1   call recurs (strngs, istrng, nodes, inodes, _ dstack, idstck, pstack, ipstck, _ xstack, ixstck, code, ip) i = dtpop (dstack, idstck) call prtast (strngs, nodes, i, dstack) end   ######################################################################
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)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#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) { for y in Y { out.print("[") for x in X { out.print(grid[x, y].pick("#", " ")) } out.println("]") } } to get(xb :int, yb :int) { return if (xb =~ x :X && yb =~ y :Y) { storage[y * gridWidth + x] } else { false } } to put(x :X, y :Y, c :boolean) { storage[y * gridWidth + x] := c } } return grid }   def mooreNeighborhood := [[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]] def computeNextLife(prevGrid, nextGrid) { for y in Y { for x in X { var neighbors := 0 for [nx, ny] ? (prevGrid[x+nx, y+ny]) in mooreNeighborhood { neighbors += 1 } def self := prevGrid[x, y] nextGrid[x, y] := (self && neighbors == 2 || neighbors == 3) } } }   var currentFrame := makeGrid() var nextFrame := makeGrid() currentFrame[1, 0] := true currentFrame[1, 1] := true currentFrame[1, 2] := true   for _ in 1..3 { def frame := nextFrame computeNextLife(currentFrame, frame) nextFrame := currentFrame currentFrame := frame println(currentFrame) }
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 See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Rust
Rust
// 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 See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Scala
Scala
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 if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#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 equal LSS - less than LEQ - less than or equal GTR - greater than GEQ - greater than or equal /I case insensitive string compares  
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 programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   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 of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#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))) (string-join (add-between (reverse (map gnirts (regexp-match* px (gnirts n)))) comma) ""))   (define (commatize s #:start (start 0) #:comma (comma ",") #:step (step 3)) (define ins-comms (insert-commas comma step)) ; specific to our comma and step   (define split-into-numbers (match-lambda [(regexp #px"^([^1-9]*)([1-9][0-9.]*)(\\S*)(.*)$" ; see below for description of bits (list _  ; the whole match (app split-into-numbers pre)  ; recur on left num  ; the number bit before any exponent or other  ; interestingness post-number  ; from exponent to the first space (app split-into-numbers post))) ; recur on right (define skip (substring num 0 start)) (match-define (regexp #px"^(.*?)(\\..*)?$" (list _  ; whole match (app ins-comms n)  ; the bit that gets the commas added (or (? string? d)  ; if it matches, then the raw string is in d (and #f (app (lambda (f) "") d))))) ; if (...)? doesn't match it returns  ; #f which we thunk to an empty string (substring num start))  ; do the match on the unskipped bit (string-append pre skip n d post-number post)] ; stitch it back together [else else]))  ; if it doesn't match leave as is    ;; kick it off (split-into-numbers s))   (module+ test (require tests/eli-tester)   (test (commatize "pi=3.14159265358979323846264338327950288419716939937510582097494459231" #:start 6 #:comma " " #:step 5) =>"pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231"   (commatize "The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." #:comma ".") =>"The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion)."   (commatize "-in Aus$+1411.8millions") =>"-in Aus$+1,411.8millions"   (commatize "===US$0017440 millions=== (in 2000 dollars)") =>"===US$0017,440 millions=== (in 2,000 dollars)"   (commatize "123.e8000 is pretty big.") =>"123.e8000 is pretty big."   (commatize "The land area of the earth is 57268900(29% of the surface) square miles.") =>"The land area of the earth is 57,268,900(29% of the surface) square miles."   (commatize "Ain't no numbers in this here words, nohow, no way, Jose.") =>"Ain't no numbers in this here words, nohow, no way, Jose."   (commatize "James was never known as 0000000007") =>"James was never known as 0000000007"   (commatize "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.") =>"Arthur Eddington wrote: I believe there are 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe."   (commatize " $-140000±100 millions.")   =>" $-140,000±100 millions." (commatize "6/9/1946 was a good year for some.") =>"6/9/1946 was a good year for some."))  
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 programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   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 of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#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 area of the earth is 57268900(29% of the surface) square miles.', 'Ain\'t no numbers in this here words, nohow, no way, Jose.', 'James was never known as 0000000007', 'Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.', ' $-140000±100 millions.', '6/9/1946 was a good year for some.' { say "Before: ", .[0]; say " After: ", .[1] ?? .[0].&commatize( |.[1] ) !! .&commatize; }   sub commatize($s, :$at = 0, :$ins = ',', :$by = 3) { $s.subst: :continue($at), :1st, / <[1..9]> <[0..9]>* /, *.flip.comb(/<{ ".**1..$by" }>/).join($ins).flip; }
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 the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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; function ToString: string; end;   { TListStringHelper }   function TListStringHelper.AllEqual: boolean; begin Result := True; if Length(self) < 2 then exit;   var first := self[0]; for var i := 1 to High(self) do if self[i] <> first then exit(False); end;   function TListStringHelper.AllLessThan: boolean; begin Result := True; if Length(self) < 2 then exit;   var last := self[0]; for var i := 1 to High(self) do begin if not (last < self[i]) then exit(False); last := self[i]; end; end;   function TListStringHelper.ToString: string; begin Result := '['; Result := Result + string.join(', ', self); Result := Result + ']'; end;   var lists: TArray<TArray<string>>;   begin lists := [['a'], ['a', 'a'], ['a', 'b']];   for var list in lists do begin writeln(list.ToString); writeln('Is AllEqual: ', list.AllEqual); writeln('Is AllLessThan: ', list.AllLessThan, #10); end;   readln; end.
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. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#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. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#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 {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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 stp if depth = 0 then print curr$; " "; names$[i] else call iterate (curr$ & " " & names$[i], i, stp, depth-1, names$) end if next i return end subroutine
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 {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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 choices = " ; choices% END   DEF FNchoose(n%, l%, p%, m%, g%(), RETURN n$()) LOCAL i%, c% IF n% = l% THEN IF !^n$() THEN FOR i% = 0 TO n%-1 PRINT " " n$(g%(i%)) ; NEXT PRINT ENDIF = 1 ENDIF FOR i% = p% TO m%-1 g%(n%) = i% c% += FNchoose(n% + 1, l%, i%, m%, g%(), n$()) NEXT = c%
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 Permutation. 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) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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) → 297242911333923795640059429176065863139989673213703918037987737481286092000 (Ank 10 10) → 3628800 (factorial 10) → 3628800 (Ank 666 42) → 1029024198692120734765388598788124551227594950478035495578451793852872815678512303375588360 1398831219998720000000000000  
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 Permutation. 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) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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 to 12:" Enum.each(1..12, &show_perm(&1, div(&1, 3))) IO.puts "\nA sample of combinations from 10 to 60:" Enum.take_every(10..60, 10) |> Enum.each(&show_comb(&1, div(&1, 3))) IO.puts "\nA sample of permutations from 5 to 15000:" Enum.each([5,50,500,1000,5000,15000], &show_perm(&1, div(&1, 3))) IO.puts "\nA sample of combinations from 100 to 1000:" Enum.take_every(100..1000, 100) |> Enum.each(&show_comb(&1, div(&1, 3))) end   defp show_perm(n, k), do: show_gen(n, k, "perm", &perm/2)   defp show_comb(n, k), do: show_gen(n, k, "comb", &comb/2)   defp show_gen(n, k, strfun, fun), do: IO.puts "#{strfun}(#{n}, #{k}) = #{show_big(fun.(n, k), 40)}"   defp show_big(n, limit) do strn = to_string(n) if String.length(strn) < limit do strn else {shown, hidden} = String.split_at(strn, limit) "#{shown}... (#{String.length(hidden)} more digits)" end end end   Combinations_permutations.test
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 also used to refer to the first stage of a lexer). Task[edit] Create a lexical analyzer for the simple programming language specified below. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a lexer module/library/class, it would be great if two versions of the solution are provided: One without the lexer module, and one with. Input Specification The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens: Operators Name Common name Character sequence Op_multiply multiply * Op_divide divide / Op_mod mod % Op_add plus + Op_subtract minus - Op_negate unary minus - Op_less less than < Op_lessequal less than or equal <= Op_greater greater than > Op_greaterequal greater than or equal >= Op_equal equal == Op_notequal not equal != Op_not unary not ! Op_assign assignment = Op_and logical and && Op_or logical or ¦¦ The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task. Symbols Name Common name Character LeftParen left parenthesis ( RightParen right parenthesis ) LeftBrace left brace { RightBrace right brace } Semicolon semi-colon ; Comma comma , Keywords Name Character sequence Keyword_if if Keyword_else else Keyword_while while Keyword_print print Keyword_putc putc Identifiers and literals These differ from the the previous tokens, in that each occurrence of them has a value associated with it. Name Common name Format description Format regex Value Identifier identifier one or more letter/number/underscore characters, but not starting with a number [_a-zA-Z][_a-zA-Z0-9]* as is Integer integer literal one or more digits [0-9]+ as is, interpreted as a number Integer char literal exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes '([^'\n]|\\n|\\\\)' the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n' String string literal zero or more characters (anything except newline or double quote), enclosed by double quotes "[^"\n]*" the characters without the double quotes and with escape sequences converted For char and string literals, the \n escape sequence is supported to represent a new-line character. For char and string literals, to represent a backslash, use \\. No other special sequences are supported. This means that: Char literals cannot represent a single quote character (value 39). String literals cannot represent strings containing double quote characters. Zero-width tokens Name Location End_of_input when the end of the input stream is reached White space Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below. "Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =). Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge. This means: keywords, identifiers, and integer literals. e.g. ifprint is recognized as an identifier, instead of the keywords if and print. e.g. 42fred is invalid, and neither recognized as a number nor an identifier. Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value). e.g. & & is invalid, and not interpreted as the && operator. For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions: if ( p /* meaning n is prime */ ) { print ( n , " " ) ; count = count + 1 ; /* number of primes found so far */ } if(p){print(n," ");count=count+1;} Complete list of token names 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_notequal Op_assign Op_and Op_or Keyword_if Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen LeftBrace RightBrace Semicolon Comma Identifier Integer String Output Format The program output should be a sequence of lines, each consisting of the following whitespace-separated fields: the line number where the token starts the column number where the token starts the token name the token value (only for Identifier, Integer, and String tokens) the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement. This task is intended to be used as part of a pipeline, with the other compiler tasks - for example: lex < hello.t | parse | gen | vm Or possibly: lex hello.t lex.out parse lex.out parse.out gen parse.out gen.out vm gen.out This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs. Diagnostics The following error conditions should be caught: Error Example Empty character constant '' Unknown escape sequence. \r Multi-character constant. 'xx' End-of-file in comment. Closing comment characters not found. End-of-file while scanning string literal. Closing string character not found. End-of-line while scanning string literal. Closing string character not found before end-of-line. Unrecognized character. | Invalid number. Starts like a number, but ends in non-numeric characters. 123abc Test Cases Input Output Test Case 1: /* Hello world */ print("Hello, World!\n"); 4 1 Keyword_print 4 6 LeftParen 4 7 String "Hello, World!\n" 4 24 RightParen 4 25 Semicolon 5 1 End_of_input Test Case 2: /* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, "\n"); 4 1 Identifier phoenix_number 4 16 Op_assign 4 18 Integer 142857 4 24 Semicolon 5 1 Keyword_print 5 6 LeftParen 5 7 Identifier phoenix_number 5 21 Comma 5 23 String "\n" 5 27 RightParen 5 28 Semicolon 6 1 End_of_input Test Case 3: /* All lexical tokens - not syntactically correct, but that will have to wait until syntax analysis */ /* Print */ print /* Sub */ - /* Putc */ putc /* Lss */ < /* If */ if /* Gtr */ > /* Else */ else /* Leq */ <= /* While */ while /* Geq */ >= /* Lbrace */ { /* Eq */ == /* Rbrace */ } /* Neq */ != /* Lparen */ ( /* And */ && /* Rparen */ ) /* Or */ || /* Uminus */ - /* Semi */ ; /* Not */ ! /* Comma */ , /* Mul */ * /* Assign */ = /* Div */ / /* Integer */ 42 /* Mod */ % /* String */ "String literal" /* Add */ + /* Ident */ variable_name /* character literal */ '\n' /* character literal */ '\\' /* character literal */ ' ' 5 16 Keyword_print 5 40 Op_subtract 6 16 Keyword_putc 6 40 Op_less 7 16 Keyword_if 7 40 Op_greater 8 16 Keyword_else 8 40 Op_lessequal 9 16 Keyword_while 9 40 Op_greaterequal 10 16 LeftBrace 10 40 Op_equal 11 16 RightBrace 11 40 Op_notequal 12 16 LeftParen 12 40 Op_and 13 16 RightParen 13 40 Op_or 14 16 Op_subtract 14 40 Semicolon 15 16 Op_not 15 40 Comma 16 16 Op_multiply 16 40 Op_assign 17 16 Op_divide 17 40 Integer 42 18 16 Op_mod 18 40 String "String literal" 19 16 Op_add 19 40 Identifier variable_name 20 26 Integer 10 21 26 Integer 92 22 26 Integer 32 23 1 End_of_input Test Case 4: /*** test printing, embedded \n and comments with lots of '*' ***/ print(42); print("\nHello World\nGood Bye\nok\n"); print("Print a slash n - \\n.\n"); 2 1 Keyword_print 2 6 LeftParen 2 7 Integer 42 2 9 RightParen 2 10 Semicolon 3 1 Keyword_print 3 6 LeftParen 3 7 String "\nHello World\nGood Bye\nok\n" 3 38 RightParen 3 39 Semicolon 4 1 Keyword_print 4 6 LeftParen 4 7 String "Print a slash n - \\n.\n" 4 33 RightParen 4 34 Semicolon 5 1 End_of_input Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Syntax Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#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 status input-status organization line sequential. data division.   file section. fd input-file. 01 input-record pic x(98).   working-storage section. 01 input-name pic x(32). 01 input-status pic xx. 01 input-length pic 99.   01 output-name pic x(32) value spaces. 01 output-status pic xx. 01 output-record pic x(64).   01 line-no pic 999 value 0. 01 col-no pic 99. 01 col-no-max pic 99. 01 col-increment pic 9 value 1. 01 start-col pic 99. 01 outx pic 99. 01 out-lim pic 99 value 48.   01 output-line value spaces. 03 out-line pic zzzz9. 03 out-column pic zzzzzz9. 03 message-area. 05 filler pic xxx. 05 token pic x(16). 05 out-value pic x(48). 05 out-integer redefines out-value pic zzzzz9. 05 out-integer1 redefines out-value pic zzzzzz9. *> to match the python lexer   01 error-record. 03 error-line pic zzzz9 value 0. 03 error-col pic zzzzzz9 value 0. 03 error-message pic x(68) value spaces.   01 scan-state pic x(16) value spaces. 01 current-character pic x. 01 previous-character pic x.   procedure division chaining input-name. start-lexer. if input-name <> spaces open input input-file if input-status = '35' string 'in lexer ' trim(input-name) ' not found' into error-message perform report-error end-if end-if perform read-input-file perform until input-status <> '00' add 1 to line-no move line-no to out-line move length(trim(input-record,trailing)) to col-no-max move 1 to col-no move space to previous-character perform until col-no > col-no-max move col-no to out-column move input-record(col-no:1) to current-character evaluate scan-state   when 'identifier' if current-character >= 'A' and <= 'Z' or (current-character >= 'a' and <= 'z') or (current-character >= '0' and <= '9') or current-character = '_' perform increment-outx move current-character to out-value(outx:1) if col-no = col-no-max perform process-identifier end-if else perform process-identifier if current-character <> space move 0 to col-increment end-if end-if   when 'integer' evaluate true when current-character >= '0' and <= '9' perform increment-outx move current-character to out-value(outx:1) if col-no = col-no-max move numval(out-value) to out-integer move 'Integer' to token end-if when current-character >= 'A' and <= 'Z' when current-character >= 'a' and <= 'z' move 'in lexer invalid integer' to error-message perform report-error when other if outx > 5 move numval(out-value) to out-integer1 *> to match the python lexer else move numval(out-value) to out-integer end-if move 'Integer' to token if current-character <> space move 0 to col-increment end-if end-evaluate   when 'comment' if previous-character = '*' and current-character = '/' move 'comment' to token end-if   when 'quote' evaluate current-character also outx when '"' also 0 string 'in lexer empty string' into error-message perform report-error when '"' also any perform increment-outx move current-character to out-value(outx:1) move 'String' to token when other if col-no = col-no-max string 'in lexer missing close quote' into error-message perform report-error else perform increment-outx move current-character to out-value(outx:1) end-if end-evaluate   when 'character' evaluate current-character also outx when "'" also 0 string 'in lexer empty character constant' into error-message perform report-error when "'" also 1 subtract 1 from ord(out-value(1:1)) giving out-integer move 'Integer' to token when "'" also 2 evaluate true when out-value(1:2) = '\n' move 10 to out-integer when out-value(1:2) = '\\' subtract 1 from ord('\') giving out-integer *> ' (workaround a Rosetta Code highlighter problem) when other string 'in lexer unknown escape sequence ' out-value(1:2) into error-message perform report-error end-evaluate move 'Integer' to token when "'" also any string 'in lexer multicharacter constant' into error-message perform report-error when other if col-no = col-no-max string 'in lexer missing close quote' into error-message perform report-error end-if perform increment-outx move current-character to out-value(outx:1) end-evaluate   when 'and' evaluate previous-character also current-character when '&' also '&' move 'Op_and' to token when other string 'in lexer AND error' into error-message perform report-error end-evaluate   when 'or' evaluate previous-character also current-character when '|' also '|' move 'Op_or' to token when other string 'in lexer OR error' into error-message perform report-error end-evaluate   when 'ambiguous' evaluate previous-character also current-character when '/' also '*' move 'comment' to scan-state subtract 1 from col-no giving start-col when '/' also any move 'Op_divide' to token move 0 to col-increment   when '=' also '=' move 'Op_equal' to token when '=' also any move 'Op_assign' to token move 0 to col-increment   when '<' also '=' move 'Op_lessequal' to token when '<' also any move 'Op_less' to token move 0 to col-increment   when '>' also '=' move 'Op_greaterequal' to token when '>'also any move 'Op_greater' to token move 0 to col-increment   when '!' also '=' move 'Op_notequal' to token when '!' also any move 'Op_not' to token move 0 to col-increment   when other display input-record string 'in lexer ' trim(scan-state) ' unknown character "' current-character '"' ' with previous character "' previous-character '"' into error-message perform report-error end-evaluate   when other move col-no to start-col evaluate current-character when space continue when >= 'A' and <= 'Z' when >= 'a' and <= 'z' move 'identifier' to scan-state move 1 to outx move current-character to out-value when >= '0' and <= '9' move 'integer' to scan-state move 1 to outx move current-character to out-value when '&' move 'and' to scan-state when '|' move 'or' to scan-state when '"' move 'quote' to scan-state move 1 to outx move current-character to out-value when "'" move 'character' to scan-state move 0 to outx when '{' move 'LeftBrace' to token when '}' move 'RightBrace' to token when '(' move 'LeftParen' to token when ')' move 'RightParen' to token when '+' move 'Op_add' to token when '-' move 'Op_subtract' to token when '*' move 'Op_multiply' to token when '%' move 'Op_mod' to token when ';' move 'Semicolon' to token when ',' move 'Comma' to token when '/' when '<' when '>' when '=' when '=' when '<' when '>' when '!' move 'ambiguous' to scan-state when other string 'in lexer unknown character "' current-character '"' into error-message perform report-error end-evaluate end-evaluate   if token <> spaces perform process-token end-if   move current-character to previous-character add col-increment to col-no move 1 to col-increment end-perform if scan-state = 'ambiguous' evaluate previous-character when '/' move 'Op_divide' to token perform process-token   when '=' move 'Op_assign' to token perform process-token   when '<' move 'Op_less' to token perform process-token   when '>' move 'Op_greater' to token perform process-token   when '!' move 'Op_not' to token perform process-token   when other string 'in lexer unresolved ambiguous "' previous-character '" at end of line' into error-message perform report-error end-evaluate end-if perform read-input-file end-perform   evaluate true when input-status <> '10' string 'in lexer ' trim(input-name) ' invalid input status ' input-status into error-message perform report-error when scan-state = 'comment' string 'in lexer unclosed comment at end of input' into error-message perform report-error end-evaluate   move 'End_of_input' to token move 1 to out-column move 1 to start-col add 1 to line-no perform process-token   close input-file stop run . process-identifier. evaluate true when out-value = 'print' move 'Keyword_print' to token move spaces to out-value when out-value = 'while' move 'Keyword_while' to token move spaces to out-value when out-value = 'if' move 'Keyword_if' to token move spaces to out-value when out-value = 'else' move 'Keyword_else' to token move spaces to out-value when out-value = 'putc' move 'Keyword_putc' to token move spaces to out-value when other move 'Identifier' to token end-evaluate . increment-outx. if outx >= out-lim string 'in lexer token value length exceeds ' out-lim into error-message perform report-error end-if add 1 to outx . process-token. if token <> 'comment' move start-col to out-column move line-no to out-line display output-line end-if move 0 to start-col move spaces to scan-state message-area . report-error. move line-no to error-line move start-col to error-col display error-record close input-file stop run with error status -1 . read-input-file. if input-name = spaces move '00' to input-status accept input-record on exception move '10' to input-status end-accept else read input-file end-if . end program lexer.
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, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#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, 1..$1;   sub value { unpack 'l', substr $binary, ($pc += 4) - 4, 4 }   my @ops = ( [ halt => sub { exit } ], [ add => sub { $stack[-2] += pop @stack } ], [ sub => sub { $stack[-2] -= pop @stack } ], [ mul => sub { $stack[-2] *= pop @stack } ], [ div => sub { $stack[-2] /= pop @stack } ], [ mod => sub { $stack[-2] %= pop @stack } ], [ not => sub { $stack[-1] = $stack[-1] ? 0 : 1 } ], [ neg => sub { $stack[-1] = - $stack[-1] } ], [ and => sub { $stack[-2] &&= $stack[-1]; pop @stack } ], [ or => sub { $stack[-2] ||= $stack[-1]; pop @stack } ], [ lt => sub { $stack[-1] = $stack[-2] < pop @stack ? 1 : 0 } ], [ gt => sub { $stack[-1] = $stack[-2] > pop @stack ? 1 : 0 } ], [ le => sub { $stack[-1] = $stack[-2] <= pop @stack ? 1 : 0 } ], [ ge => sub { $stack[-1] = $stack[-2] >= pop @stack ? 1 : 0 } ], [ ne => sub { $stack[-1] = $stack[-2] != pop @stack ? 1 : 0 } ], [ eq => sub { $stack[-1] = $stack[-2] == pop @stack ? 1 : 0 } ], [ prts => sub { print $strings[pop @stack] } ], [ prti => sub { print pop @stack } ], [ prtc => sub { print chr pop @stack } ], [ store => sub { $data[value()] = pop @stack } ], [ fetch => sub { push @stack, $data[value()] // 0 } ], [ push => sub { push @stack, value() } ], [ jmp => sub { $pc += value() - 4 } ], [ jz => sub { $pc += pop @stack ? 4 : value() - 4 } ], ); my %op2n = map { $ops[$_][0], $_ } 0..$#ops; # map name to op number   while(<>) { /^ *\d+ +(\w+)/ or die "bad line $_"; # format error $binary .= chr( $op2n{$1} // die "$1 not defined" ) . # op code (/\((-?\d+)\)|(\d+)]?$/ and pack 'l', $+); # 4 byte value }   $ops[vec($binary, $pc++, 8)][1]->() while 1; # run it
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 Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#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 ge Equal eq Greater gt NotEqual ne Negate neg );   sub tree { my ($A, $B) = ( '_' . ++$pairsym, '_' . ++$pairsym ); # labels for jumps my $line = <> // return ''; (local $_, my $arg) = $line =~ /^(\w+|;)\s+(.*)/ or die "bad input $line"; /Identifier/ ? "fetch [@{[ $names{$arg} //= $namecount++ ]}]\n" : /Sequence/ ? tree() . tree() : /Integer/ ? "push $arg\n" : /String/ ? "push @{[ $strings{$arg} //= $stringcount++ ]}\n" : /Assign/ ? join '', reverse tree() =~ s/fetch/store/r, tree() : /While/ ? "$A:\n@{[ tree() ]}jz $B\n@{[ tree() ]}jmp $A\n$B:\n" : /If/ ? tree() . "jz $A\n@{[ !<> . # !<> skips second 'If' tree() ]}jmp $B\n$A:\n@{[ tree() ]}$B:\n" : /;/ ? '' : tree() . tree() . ($opnames{$_} // lc) . "\n"; }   $_ = tree() . "halt\n";   s/^jmp\s+(\S+)\n(_\d+:\n)\1:\n/$2/gm; # remove jmp next s/^(?=[a-z]\w*(.*))/ # add locations (sprintf("%4d ", $pc), $pc += $1 ? 5 : 1)[0] /gem; my %labels = /^(_\d+):(?=(?:\n_\d+:)*\n *(\d+) )/gm; # pc addr of labels s/^ *(\d+) j(?:z|mp) *\K(_\d+)$/ (@{[ # fix jumps $labels{$2} - $1 - 1]}) $labels{$2}/gm; s/^_\d+.*\n//gm; # remove labels   print "Datasize: $namecount Strings: $stringcount\n"; print "$_\n" for sort { $strings{$a} <=> $strings{$b} } keys %strings; print;
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Measure a relative performance of sorting algorithms implementations. Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures). Consider three type of input sequences:   ones: sequence of all 1's.   Example: {1, 1, 1, 1, 1}   range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}   shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8} Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm). For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations. Preliminary subtask:   Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort   Query Performance   Write float arrays to a text file   Plot x, y arrays   Polynomial Fitting General steps:   Define sorting routines to be considered.   Define appropriate sequence generators and write timings.   Plot timings.   What conclusions about relative performance of the sorting routines could be made based on the plots?
#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 pack [canvas $w.c -background white] pack [canvas $w.legend -background white] update plot_log10 $w.c $w.legend $title $xlabel $ylabel $xs $ys $labels $shapes $colours $w.c config -scrollregion [$w.c bbox all] update }   proc plot_log10 {canvas legend title xlabel ylabel xs ys labels shapes colours} { global xfac yfac set log10_xs [map {_ {log10 $_}} $xs] foreach series $ys { lappend log10_ys [map {_ {log10 $_}} $series] } set maxx [max {*}$log10_xs] set yvalues [lsort -real [struct::list flatten $log10_ys]] set firstInf [lsearch $yvalues Inf] set maxy [lindex $yvalues [expr {$firstInf == -1 ? [llength $yvalues] - 1 : $firstInf - 1}]]   set xfac [expr {[winfo width $canvas] * 0.8/$maxx}] set yfac [expr {[winfo height $canvas] * 0.8/$maxy}]   scale $canvas x 0 $maxx $xfac "log10($xlabel)" scale $canvas y 0 $maxy $yfac "log10($ylabel)" $maxx $xfac   $legend create text 30 0 -text $title -anchor nw set count 1 foreach series $log10_ys shape $shapes colour $colours label $labels { plotxy $canvas $log10_xs $series $shape $colour legenditem $legend [incr count] $shape $colour $label } }   proc map {lambda list} { set res [list] foreach item $list {lappend res [apply $lambda $item]} return $res }   proc legenditem {legend pos shape colour label} { set y [expr {$pos * 15}] $shape $legend 20 $y -fill $colour $legend create text 30 $y -text $label -anchor w }   # The actual plotting engine proc plotxy {canvas _xs _ys shape colour} { global xfac yfac foreach x $_xs y $_ys { if {$y < Inf} { lappend xs $x lappend ys $y } } set coords [list] foreach x $xs y $ys { set coord_x [expr {$x*$xfac}] set coord_y [expr {-$y*$yfac}] $shape $canvas $coord_x $coord_y -fill $colour lappend coords $coord_x $coord_y } $canvas create line $coords -smooth true } # Rescales the contents of the given canvas proc scale {canvas direction from to fac label {other_to 0} {other_fac 0}} { set f [expr {$from*$fac}] set t [expr {$to*$fac}] switch -- $direction { x { set f [expr {$from * $fac}] set t [expr {$to * $fac}] # create x-axis $canvas create line $f 0 $t 0 $canvas create text $f 0 -anchor nw -text $from $canvas create text $t 0 -anchor n -text [format "%.1f" $to] $canvas create text [expr {($f+$t)/2}] 0 -anchor n -text $label   } y { set f [expr {$from * -$fac}] set t [expr {$to * -$fac}] # create y-axis $canvas create line 0 $f 0 $t $canvas create text 0 $f -anchor se -text $from $canvas create text 0 $t -anchor e -text [format "%.1f" $to] $canvas create text 0 [expr {($f+$t)/2}] -anchor e -text $label # create gridlines set xmax [expr {$other_to * $other_fac}] for {set i 1} {$i < $to} {incr i} { set y [expr {$i * -$fac}] $canvas create line 0 $y $xmax $y -dash . } } } } # Helper to make points, which are otherwise not a native item type proc dot {canvas x y args} { set id [$canvas create oval [expr {$x-3}] [expr {$y-3}] \ [expr {$x+3}] [expr {$y+3}]] $canvas itemconfigure $id {*}$args } proc square {canvas x y args} { set id [$canvas create rectangle [expr {$x-3}] [expr {$y-3}] \ [expr {$x+3}] [expr {$y+3}]] $canvas itemconfigure $id {*}$args } proc cross {canvas x y args} { set l1 [$canvas create line [expr {$x-3}] $y [expr {$x+3}] $y] set l2 [$canvas create line $x [expr {$y-3}] $x [expr {$y+3}]] $canvas itemconfigure $l1 {*}$args $canvas itemconfigure $l2 {*}$args } proc x {canvas x y args} { set l1 [$canvas create line [expr {$x-3}] [expr {$y-3}] [expr {$x+3}] [expr {$y+3}]] set l2 [$canvas create line [expr {$x+3}] [expr {$y-3}] [expr {$x-3}] [expr {$y+3}]] $canvas itemconfigure $l1 {*}$args $canvas itemconfigure $l2 {*}$args } proc triangleup {canvas x y args} { set id [$canvas create polygon $x [expr {$y-4}] \ [expr {$x+4}] [expr {$y+4}] \ [expr {$x-4}] [expr {$y+4}]] $canvas itemconfigure $id {*}$args } proc triangledown {canvas x y args} { set id [$canvas create polygon $x [expr {$y+4}] \ [expr {$x+4}] [expr {$y-4}] \ [expr {$x-4}] [expr {$y-4}]] $canvas itemconfigure $id {*}$args }   wm withdraw .   ##################################################################### # list creation procedures proc ones n { lrepeat $n 1 } proc reversed n { while {[incr n -1] >= 0} { lappend result $n } return $result } proc random n { for {set i 0} {$i < $n} {incr i} { lappend result [expr {int($n * rand())}] } return $result }   set algorithms {lsort quicksort shellsort insertionsort bubblesort mergesort} set sizes {1 10 100 1000 10000 100000} set types {ones reversed random} set shapes {dot square cross triangleup triangledown x} set colours {red blue black brown yellow black}   # create some lists to be used by all sorting algorithms array set lists {} foreach size $sizes { foreach type $types { set lists($type,$size) [$type $size] } }   set runs 10   # header fconfigure stdout -buffering none puts -nonewline [format "%-16s" "list length:"] foreach size $sizes { puts -nonewline [format " %10d" $size] } puts ""   # perform the sort timings and output results foreach type $types { puts "\nlist type: $type" set times [list] foreach algo $algorithms { set errs [list] set thesetimes [list] $algo {} ;# call it once to ensure it's compiled   puts -nonewline [format "  %-13s" $algo] foreach size $sizes { # some implementations are just too slow if {$type ne "ones" && ( ($algo eq "insertionsort" && $size > 10000) || ($algo eq "bubblesort" && $size > 1000)) } { set time Inf } else { # OK, do it if {[catch {time [list $algo $lists($type,$size)] $runs} result] != 0} { set time Inf lappend errs $result } else { set time [lindex [split $result] 0] } } lappend thesetimes $time puts -nonewline [format " %10s" $time] } puts "" if {[llength $errs] > 0} { puts [format "  %s" [join $errs "\n "]] } lappend times $thesetimes } create_log10_plot "Sorting a '$type' list" size time $sizes $times $algorithms $shapes $colours } puts "\ntimes in microseconds, average of $runs runs"
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 | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 safeguard to update max const } list: array[specimenMinimum..specimenMaximum] of string(24) value [A: specimenA; B: specimenB; C: specimenC; D: specimenD]; lengthRelationship: array[specimen] of specimens;   procedure analyzeLengths; var left, right: specimen; begin for left := specimenMinimum to specimenMaximum do begin for right := specimenMinimum to specimenMaximum do begin if length(list[left]) < length(list[right]) then begin lengthRelationship[right] := lengthRelationship[right] + [right] end end end end;   procedure printSortedByLengths; var i: ord(specimenMinimum)..ord(specimenMaximum); s: specimen; begin { first the string longer than all other strings } { lastly print the string not longer than any other string } for i := ord(specimenMaximum) downto ord(specimenMinimum) do begin { for demonstration purposes: iterate over a set } for s in [specimenMinimum..specimenMaximum] do begin { card returns the cardinality ("population count") } if card(lengthRelationship[s]) = i then begin writeLn(length(list[s]):8, ' ', list[s]) end end end end;   begin analyzeLengths; printSortedByLengths end.
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 input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a parser module/library/class, it would be great if two versions of the solution are provided: One without the parser module, and one with. Grammar The simple programming language to be analyzed is more or less a (very tiny) subset of C. The formal grammar in Extended Backus-Naur Form (EBNF):   stmt_list = {stmt} ;   stmt = ';' | Identifier '=' expr ';' | 'while' paren_expr stmt | 'if' paren_expr stmt ['else' stmt] | 'print' '(' prt_list ')' ';' | 'putc' paren_expr ';' | '{' stmt_list '}'  ;   paren_expr = '(' expr ')' ;   prt_list = (string | expr) {',' (String | expr)} ;   expr = and_expr {'||' and_expr} ; and_expr = equality_expr {'&&' equality_expr} ; equality_expr = relational_expr [('==' | '!=') relational_expr] ; relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ; addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ; multiplication_expr = primary {('*' | '/' | '%') primary } ; primary = Identifier | Integer | '(' expr ')' | ('+' | '-' | '!') primary  ; The resulting AST should be formulated as a Binary Tree. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast The following table shows the input to lex, lex output, and the AST produced by the parser Input to lex Output from lex, input to parse Output from parse count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Specifications List of node type names Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or In the text below, Null/Empty nodes are represented by ";". Non-terminal (internal) nodes For Operators, the following nodes should be created: Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or For each of the above nodes, the left and right sub-nodes are the operands of the respective operation. In pseudo S-Expression format: (Operator expression expression) Negate, Not For these node types, the left node is the operand, and the right node is null. (Operator expression ;) Sequence - sub-nodes are either statements or Sequences. If - left node is the expression, the right node is If node, with it's left node being the if-true statement part, and the right node being the if-false (else) statement part. (If expression (If statement else-statement)) If there is not an else, the tree becomes: (If expression (If statement ;)) Prtc (Prtc (expression) ;) Prts (Prts (String "the string") ;) Prti (Prti (Integer 12345) ;) While - left node is the expression, the right node is the statement. (While expression statement) Assign - left node is the left-hand side of the assignment, the right node is the right-hand side of the assignment. (Assign Identifier expression) Terminal (leaf) nodes: Identifier: (Identifier ident_name) Integer: (Integer 12345) String: (String "Hello World!") ";": Empty node Some simple examples Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path. This simple program: a=11; Produces the following AST, encoded as a binary tree: Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node: (1) Sequence (2) |-- ; (3) |-- Assign (4) |-- Identifier: a (5) |-- Integer: 11 In flattened form: (1) Sequence (2) ; (3) Assign (4) Identifier a (5) Integer 11 This program: a=11; b=22; c=33; Produces the following AST: ( 1) Sequence ( 2) |-- Sequence ( 3) | |-- Sequence ( 4) | | |-- ; ( 5) | | |-- Assign ( 6) | | |-- Identifier: a ( 7) | | |-- Integer: 11 ( 8) | |-- Assign ( 9) | |-- Identifier: b (10) | |-- Integer: 22 (11) |-- Assign (12) |-- Identifier: c (13) |-- Integer: 33 In flattened form: ( 1) Sequence ( 2) Sequence ( 3) Sequence ( 4) ; ( 5) Assign ( 6) Identifier a ( 7) Integer 11 ( 8) Assign ( 9) Identifier b (10) Integer 22 (11) Assign (12) Identifier c (13) Integer 33 Pseudo-code for the parser. Uses Precedence Climbing for expression parsing, and Recursive Descent for statement parsing. The AST is also built: def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error()   while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q))   return x   def paren_expr() expect("(") x = expr(0) expect(")") return x   def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0))   t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t   def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t Once the AST is built, it should be output in a flattened format. This can be as simple as the following def prt_ast(t) if t == NULL print(";\n") else print(t.node_type) if t.node_type in [Identifier, Integer, String] # leaf node print the value of the Ident, Integer or String, "\n" else print("\n") prt_ast(t.left) prt_ast(t.right) If the AST is correctly built, loading it into a subsequent program should be as simple as def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) Finally, the AST can also be tested by running it against one of the AST Interpreter solutions. Test program, assuming this is in a file called prime.t lex <prime.t | parse Input to lex Output from lex, input to parse Output from parse /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 4 1 Identifier count 4 7 Op_assign 4 9 Integer 1 4 10 Semicolon 5 1 Identifier n 5 3 Op_assign 5 5 Integer 1 5 6 Semicolon 6 1 Identifier limit 6 7 Op_assign 6 9 Integer 100 6 12 Semicolon 7 1 Keyword_while 7 7 LeftParen 7 8 Identifier n 7 10 Op_less 7 12 Identifier limit 7 17 RightParen 7 19 LeftBrace 8 5 Identifier k 8 6 Op_assign 8 7 Integer 3 8 8 Semicolon 9 5 Identifier p 9 6 Op_assign 9 7 Integer 1 9 8 Semicolon 10 5 Identifier n 10 6 Op_assign 10 7 Identifier n 10 8 Op_add 10 9 Integer 2 10 10 Semicolon 11 5 Keyword_while 11 11 LeftParen 11 12 LeftParen 11 13 Identifier k 11 14 Op_multiply 11 15 Identifier k 11 16 Op_lessequal 11 18 Identifier n 11 19 RightParen 11 21 Op_and 11 24 LeftParen 11 25 Identifier p 11 26 RightParen 11 27 RightParen 11 29 LeftBrace 12 9 Identifier p 12 10 Op_assign 12 11 Identifier n 12 12 Op_divide 12 13 Identifier k 12 14 Op_multiply 12 15 Identifier k 12 16 Op_notequal 12 18 Identifier n 12 19 Semicolon 13 9 Identifier k 13 10 Op_assign 13 11 Identifier k 13 12 Op_add 13 13 Integer 2 13 14 Semicolon 14 5 RightBrace 15 5 Keyword_if 15 8 LeftParen 15 9 Identifier p 15 10 RightParen 15 12 LeftBrace 16 9 Keyword_print 16 14 LeftParen 16 15 Identifier n 16 16 Comma 16 18 String " is prime\n" 16 31 RightParen 16 32 Semicolon 17 9 Identifier count 17 15 Op_assign 17 17 Identifier count 17 23 Op_add 17 25 Integer 1 17 26 Semicolon 18 5 RightBrace 19 1 RightBrace 20 1 Keyword_print 20 6 LeftParen 20 7 String "Total primes found: " 20 29 Comma 20 31 Identifier count 20 36 Comma 20 38 String "\n" 20 42 RightParen 20 43 Semicolon 21 1 End_of_input Sequence Sequence Sequence Sequence Sequence ; Assign Identifier count Integer 1 Assign Identifier n Integer 1 Assign Identifier limit Integer 100 While Less Identifier n Identifier limit Sequence Sequence Sequence Sequence Sequence ; Assign Identifier k Integer 3 Assign Identifier p Integer 1 Assign Identifier n Add Identifier n Integer 2 While And LessEqual Multiply Identifier k Identifier k Identifier n Identifier p Sequence Sequence ; Assign Identifier p NotEqual Multiply Divide Identifier n Identifier k Identifier k Identifier n Assign Identifier k Add Identifier k Integer 2 If Identifier p If Sequence Sequence ; Sequence Sequence ; Prti Identifier n ; Prts String " is prime\n" ; Assign Identifier count Add Identifier count Integer 1 ; Sequence Sequence Sequence ; Prts String "Total primes found: " ; Prti Identifier count ; Prts String "\n" ; Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#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, BranchNode("And", _, _))), "Op_equal" -> (null, InfixOperator(30, LeftAssoc, BranchNode("Equal", _, _))), "Op_notequal" -> (null, InfixOperator(30, LeftAssoc, BranchNode("NotEqual", _, _))), "Op_less" -> (null, InfixOperator(40, LeftAssoc, BranchNode("Less", _, _))), "Op_lessequal" -> (null, InfixOperator(40, LeftAssoc, BranchNode("LessEqual", _, _))), "Op_greater" -> (null, InfixOperator(40, LeftAssoc, BranchNode("Greater", _, _))), "Op_greaterequal" -> (null, InfixOperator(40, LeftAssoc, BranchNode("GreaterEqual", _, _))), "Op_add" -> (PrefixOperator(30, identity), InfixOperator(50, LeftAssoc, BranchNode("Add", _, _))), "Op_minus" -> (PrefixOperator(70, BranchNode("Negate", _, TerminalNode)), InfixOperator( 50, LeftAssoc, BranchNode("Subtract", _, _))), "Op_multiply" -> (null, InfixOperator(60, LeftAssoc, BranchNode("Multiply", _, _))), "Op_divide" -> (null, InfixOperator(60, LeftAssoc, BranchNode("Divide", _, _))), "Op_mod" -> (null, InfixOperator(60, RightAssoc, BranchNode("Mod", _, _))), "Op_not" -> (PrefixOperator(70, BranchNode("Not", _)), null), "LeftParen" -> null, "RightParen" -> null )   def apply = new SyntaxAnalyzer(symbols)   abstract class Node case class LeafNode(name: String, value: String) extends Node case class BranchNode(name: String, left: Node, right: Node = TerminalNode) extends Node case object TerminalNode extends Node   abstract class Assoc case object LeftAssoc extends Assoc case object RightAssoc extends Assoc   abstract class Operator case class InfixOperator(prec: Int, assoc: Assoc, compute: (Node, Node) => Node) extends Operator case class PrefixOperator(prec: Int, compute: Node => Node) extends Operator   }   class SyntaxAnalyzer(symbols: Map[String, (SyntaxAnalyzer.PrefixOperator, SyntaxAnalyzer.InfixOperator)]) { import SyntaxAnalyzer.{BranchNode, InfixOperator, LeafNode, LeftAssoc, Node, PrefixOperator, TerminalNode}   def fromStdin = fromSource(Source.stdin)   def fromString(src: String) = fromSource(Source.fromString(src))   def fromSource(s: Source) = { val tokens = ((s.getLines map (_.trim.split(" +", 4)) map { case Array(line, col, name) => symbols get name match { case None | Some(null) => SimpleToken(line.toInt, col.toInt, name) case Some(operators) => OperatorToken(line.toInt, col.toInt, name, operators) } case Array(line, col, name, value) => ValueToken(line.toInt, col.toInt, name, value) }) toStream)   flatten(parse(tokens)) }   def flatten(n: Node): Unit = n match { case TerminalNode => println(";") case LeafNode(name, value) => println(s"$name $value") case BranchNode(name, left, right) => println(name) flatten(left) flatten(right) }   def parse(toks: Stream[Token]) = { var cur = toks   def next = cur = cur.tail   def token = cur.head   def consume = { val res = token   next res }   def accept(name: String) = if (token.name == name) { next true } else false   def expect(name: String, error: String = null) = if (token.name != name) sys.error(if (error eq null) s"expected $name, found ${token.name}" else s"$error: $token") else next   def expression(minPrec: Int): Node = { def infixOperator = token.asInstanceOf[OperatorToken].operators._2   def isInfix = token.isInstanceOf[OperatorToken] && infixOperator != null   var result = consume match { case SimpleToken(_, _, "LeftParen") => val result = expression(0)   expect("RightParen", "expected closing parenthesis") result case ValueToken(_, _, name, value) => LeafNode(name, value) case OperatorToken(_, _, _, (prefix, _)) if prefix ne null => prefix.compute(expression(prefix.prec)) case OperatorToken(_, _, _, (_, infix)) if infix ne null => sys.error(s"expected a primitive expression, not an infix operator: $token") }   while (isInfix && infixOperator.prec >= minPrec) { val InfixOperator(prec, assoc, compute) = infixOperator val nextMinPrec = if (assoc == LeftAssoc) prec + 1 else prec   next result = compute(result, expression(nextMinPrec)) }   result }   def parenExpression = { expect("LeftParen")   val e = expression(0)   expect("RightParen") e }   def statement: Node = { var stmt: Node = TerminalNode   if (accept("Keyword_if")) stmt = BranchNode("If", parenExpression, BranchNode("If", statement, if (accept("Keyword_else")) statement else TerminalNode)) else if (accept("Keyword_putc")) { stmt = BranchNode("Prtc", parenExpression) expect("Semicolon") } else if (accept("Keyword_print")) { expect("LeftParen")   do { val e = if (token.name == "String") BranchNode("Prts", LeafNode("String", consume.asInstanceOf[ValueToken].value)) else BranchNode("Prti", expression(0))   stmt = BranchNode("Sequence", stmt, e) } while (accept("Comma"))   expect("RightParen") expect("Semicolon") } else if (token.name == "Semicolon") next else if (token.name == "Identifier") { val ident = LeafNode("Identifier", consume.asInstanceOf[ValueToken].value)   expect("Op_assign") stmt = BranchNode("Assign", ident, expression(0)) expect("Semicolon") } else if (accept("Keyword_while")) stmt = BranchNode("While", parenExpression, statement) else if (accept("LeftBrace")) { while (token.name != "RightBrace" && token.name != "End_of_input") { stmt = BranchNode("Sequence", stmt, statement) }   expect("RightBrace") } else sys.error(s"syntax error: $token")   stmt }   var tree: Node = TerminalNode   do { tree = BranchNode("Sequence", tree, statement) } while (token.name != "End_of_input")   expect("End_of_input") tree }   abstract class Token { val line: Int; val col: Int; val name: String }   case class SimpleToken(line: Int, col: Int, name: String) extends Token case class ValueToken(line: Int, col: Int, name: String, value: String) extends Token case class OperatorToken(line: Int, col: Int, name: String, operators: (PrefixOperator, InfixOperator)) extends Token   }  
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)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#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 . . . . subr update swap f[] p[] for r = 1 to n - 1 sm = 0 i = r * n sr = p[i - n + 1] + p[i + 1] + p[i + n + 1] for c = 1 to n - 1 i += 1 sl = sm sm = sr sr = p[i - n + 1] + p[i + 1] + p[i + n + 1] s = sl + sm + sr if s = 3 or s = 4 and p[i] = 1 f[i] = 1 else f[i] = 0 . . . . on timer call update call show timer 0.2 . on mouse_down c = mouse_x div f r = mouse_y div f i = r * n + c + n + 1 f[i] = 1 - f[i] call show timer 3 . len f[] n * n + n + 1 len p[] n * n + n + 1 call init timer 0
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 See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Scheme
Scheme
(define-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 See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Seed7
Seed7
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 if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#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 optional): CASE expression OF WHEN value1: statements WHEN value2: statements ... OTHERWISE: statements ENDCASE   REM ON ... GOTO (ELSE clause is optional): ON expression% GOTO dest1, dest2 ... ELSE statements   REM ON ...GOSUB (ELSE clause is optional): ON expression% GOSUB dest1, dest2 ... ELSE statements   REM ON ... PROC (ELSE clause is optional): ON expression% PROCone, PROCtwo ... ELSE statements
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 programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   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 of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#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 dollars)" @.5= "123.e8000 is pretty big." @.6= "The land area of the earth is 57268900(29% of the surface) square miles." @.7= "Ain't no numbers in this here words, nohow, no way, Jose." @.8= "James was never known as 0000000007" @.9= "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." @.10= " $-140000±100 millions." @.11= "6/9/1946 was a good year for some."   do i=1 while @.i\==''; if i\==1 then say /*process each string.*/ say 'before──►'@.i /*show the before str.*/ if i==1 then say ' after──►'comma(@.i, 'blank', 5, , 6) /* p=5, start=6. */ if i==2 then say ' after──►'comma(@.i, ".") /*comma=decimal point.*/ if i>2 then say ' after──►'comma(@.i) /*use the defaults. */ end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ comma: procedure; parse arg x,sep,period,times,start /*obtain true case arguments.*/ arg ,sepU /* " uppercase 2nd arg. */ bla= ' ' /*literal to hold a "blank".*/ sep= word(sep ',', 1) /*define comma (string/char.)*/ if sepU=='BLANK' then sep= bla /*allow the use of 'BLANK'. */ period= word(period 3, 1) /*defined "period" to be used*/ times= word(times 999999999, 1) /*limits # changes to be made*/ start= word(start 1 , 1) /*where to start commatizing.*/ /* [↓] various error tests. */ if \datatype(period, 'W') | , /*test for a whole number. */ \datatype(times , 'W') | , /* " " " " " */ \datatype(start , 'W') | , /* " " " " " */ start <1 | , /*start can't be less then 1.*/ arg() >5 then return x /*# of args can't be > 5. */ /* [↑] some arg is invalid. */ op= period /*save the original period. */ period= abs(period) /*use the absolute value. */ n= x'.9' /*a literal string for end. */ digs= 123456789 /*the legal digits for start.*/ digsz= 1234567890 /* " " " " fin. */ digszp= 1234567890. /* " " " " fin. */ /* [↓] note: no zero in digs*/ if op<0 then do /*Negative? Treat as chars. */ beg= start /*begin at the start. */ L= length(x) /*obtain the length of X. */ fin= L - verify( reverse(x), bla) + 1 /*find the ending of the num.*/ end /* [↑] find number ending. */ else do /*Positive? Treat as numbers*/ beg= verify(n, digs, "M",start) /*find beginning of number. */ v2=max(verify(n, digszp,'M',start),1) /*end of the usable number. */ fin=verify(n, digsz, , v2) -period -1 /*adjust the ending (fin). */ end /* [↑] find ending of number*/ #= 0 /*the count of changes made. */ if beg>0 & fin>0 then /* [↓] process TIMES times*/ do j=fin to beg by -period while #<times x= insert(sep, x, j) /*insert a comma into string.*/ #= # + 1 /*bump the count of changes. */ end /*j*/ /*(maybe no changes are made)*/ return x /*return the commatized str. */
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 the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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();   ^ nil == former.zipBy(later, (prev,next => next <= prev )).seekEach:(b => b) } }   testCases = new string[][]{ new string[]{"AA","BB","CC"}, new string[]{"AA","AA","AA"}, new string[]{"AA","CC","BB"}, new string[]{"AA","ACB","BB","CC"}, new string[]{"single_element"}};   public program() { testCases.forEach:(list) { console.printLine(list.asEnumerable()," all equal - ",list.isEqual()); console.printLine(list.asEnumerable()," ascending - ",list.isAscending()) };   console.readChar() }
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. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#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 quibble(d, n) }
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 {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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 & ~ ) | !result ) ) ) & out$(choices$(2.iced jam plain)) & out$(choices$(3.iced jam plain butter marmite tahin fish salad onion grass):?+[?N&!N) );
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 {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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"); }   // idea: custom number system with 2s complement like 0b10...0==MIN stop case void combination_with_repetiton(int n, int k) { while (1) { for (int i = k; i > 0; i -= 1) { if (pos[i] > n - 1) // if number spilled over: xx0(n-1)xx { pos[i - 1] += 1; // set xx1(n-1)xx for (int j = i; j <= k; j += 1) pos[j] = pos[j - 1]; // set xx11..1 } } if (pos[0] > 0) // stop condition: 1xxxx break; printDonuts(k); pos[k] += 1; // xxxxN -> xxxxN+1 } }   int main() { combination_with_repetiton(3, 2); return 0; }  
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 Permutation. 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) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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"), [show_perm({N, N div 3}) || N <- lists:seq(1, 12)], io:format("\nA sample of combinations from 10 to 60:\n"), [show_comb({N, N div 3}) || N <- lists:seq(10, 60, 10)], io:format("\nA sample of permutations from 5 to 15000:\n"), [show_perm({N, N div 3}) || N <- [5,50,500,1000,5000,15000]], io:format("\nA sample of combinations from 100 to 1000:\n"), [show_comb({N, N div 3}) || N <- lists:seq(100, 1000, 100)], ok.   show_perm({N, K}) -> show_gen(N, K, "perm", fun perm/2).   show_comb({N, K}) -> show_gen(N, K, "comb", fun comb/2).   show_gen(N, K, StrFun, Fun) -> io:format("~s(~p, ~p) = ~s\n",[StrFun, N, K, show_big(Fun(N, K), 40)]).   show_big(N, Limit) -> StrN = integer_to_list(N), case length(StrN) < Limit of true -> StrN; false -> {Shown, Hidden} = lists:split(Limit, StrN), io_lib:format("~s... (~p more digits)", [Shown, length(Hidden)]) end.  
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 also used to refer to the first stage of a lexer). Task[edit] Create a lexical analyzer for the simple programming language specified below. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a lexer module/library/class, it would be great if two versions of the solution are provided: One without the lexer module, and one with. Input Specification The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens: Operators Name Common name Character sequence Op_multiply multiply * Op_divide divide / Op_mod mod % Op_add plus + Op_subtract minus - Op_negate unary minus - Op_less less than < Op_lessequal less than or equal <= Op_greater greater than > Op_greaterequal greater than or equal >= Op_equal equal == Op_notequal not equal != Op_not unary not ! Op_assign assignment = Op_and logical and && Op_or logical or ¦¦ The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task. Symbols Name Common name Character LeftParen left parenthesis ( RightParen right parenthesis ) LeftBrace left brace { RightBrace right brace } Semicolon semi-colon ; Comma comma , Keywords Name Character sequence Keyword_if if Keyword_else else Keyword_while while Keyword_print print Keyword_putc putc Identifiers and literals These differ from the the previous tokens, in that each occurrence of them has a value associated with it. Name Common name Format description Format regex Value Identifier identifier one or more letter/number/underscore characters, but not starting with a number [_a-zA-Z][_a-zA-Z0-9]* as is Integer integer literal one or more digits [0-9]+ as is, interpreted as a number Integer char literal exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes '([^'\n]|\\n|\\\\)' the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n' String string literal zero or more characters (anything except newline or double quote), enclosed by double quotes "[^"\n]*" the characters without the double quotes and with escape sequences converted For char and string literals, the \n escape sequence is supported to represent a new-line character. For char and string literals, to represent a backslash, use \\. No other special sequences are supported. This means that: Char literals cannot represent a single quote character (value 39). String literals cannot represent strings containing double quote characters. Zero-width tokens Name Location End_of_input when the end of the input stream is reached White space Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below. "Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =). Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge. This means: keywords, identifiers, and integer literals. e.g. ifprint is recognized as an identifier, instead of the keywords if and print. e.g. 42fred is invalid, and neither recognized as a number nor an identifier. Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value). e.g. & & is invalid, and not interpreted as the && operator. For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions: if ( p /* meaning n is prime */ ) { print ( n , " " ) ; count = count + 1 ; /* number of primes found so far */ } if(p){print(n," ");count=count+1;} Complete list of token names 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_notequal Op_assign Op_and Op_or Keyword_if Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen LeftBrace RightBrace Semicolon Comma Identifier Integer String Output Format The program output should be a sequence of lines, each consisting of the following whitespace-separated fields: the line number where the token starts the column number where the token starts the token name the token value (only for Identifier, Integer, and String tokens) the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement. This task is intended to be used as part of a pipeline, with the other compiler tasks - for example: lex < hello.t | parse | gen | vm Or possibly: lex hello.t lex.out parse lex.out parse.out gen parse.out gen.out vm gen.out This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs. Diagnostics The following error conditions should be caught: Error Example Empty character constant '' Unknown escape sequence. \r Multi-character constant. 'xx' End-of-file in comment. Closing comment characters not found. End-of-file while scanning string literal. Closing string character not found. End-of-line while scanning string literal. Closing string character not found before end-of-line. Unrecognized character. | Invalid number. Starts like a number, but ends in non-numeric characters. 123abc Test Cases Input Output Test Case 1: /* Hello world */ print("Hello, World!\n"); 4 1 Keyword_print 4 6 LeftParen 4 7 String "Hello, World!\n" 4 24 RightParen 4 25 Semicolon 5 1 End_of_input Test Case 2: /* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, "\n"); 4 1 Identifier phoenix_number 4 16 Op_assign 4 18 Integer 142857 4 24 Semicolon 5 1 Keyword_print 5 6 LeftParen 5 7 Identifier phoenix_number 5 21 Comma 5 23 String "\n" 5 27 RightParen 5 28 Semicolon 6 1 End_of_input Test Case 3: /* All lexical tokens - not syntactically correct, but that will have to wait until syntax analysis */ /* Print */ print /* Sub */ - /* Putc */ putc /* Lss */ < /* If */ if /* Gtr */ > /* Else */ else /* Leq */ <= /* While */ while /* Geq */ >= /* Lbrace */ { /* Eq */ == /* Rbrace */ } /* Neq */ != /* Lparen */ ( /* And */ && /* Rparen */ ) /* Or */ || /* Uminus */ - /* Semi */ ; /* Not */ ! /* Comma */ , /* Mul */ * /* Assign */ = /* Div */ / /* Integer */ 42 /* Mod */ % /* String */ "String literal" /* Add */ + /* Ident */ variable_name /* character literal */ '\n' /* character literal */ '\\' /* character literal */ ' ' 5 16 Keyword_print 5 40 Op_subtract 6 16 Keyword_putc 6 40 Op_less 7 16 Keyword_if 7 40 Op_greater 8 16 Keyword_else 8 40 Op_lessequal 9 16 Keyword_while 9 40 Op_greaterequal 10 16 LeftBrace 10 40 Op_equal 11 16 RightBrace 11 40 Op_notequal 12 16 LeftParen 12 40 Op_and 13 16 RightParen 13 40 Op_or 14 16 Op_subtract 14 40 Semicolon 15 16 Op_not 15 40 Comma 16 16 Op_multiply 16 40 Op_assign 17 16 Op_divide 17 40 Integer 42 18 16 Op_mod 18 40 String "String literal" 19 16 Op_add 19 40 Identifier variable_name 20 26 Integer 10 21 26 Integer 92 22 26 Integer 32 23 1 End_of_input Test Case 4: /*** test printing, embedded \n and comments with lots of '*' ***/ print(42); print("\nHello World\nGood Bye\nok\n"); print("Print a slash n - \\n.\n"); 2 1 Keyword_print 2 6 LeftParen 2 7 Integer 42 2 9 RightParen 2 10 Semicolon 3 1 Keyword_print 3 6 LeftParen 3 7 String "\nHello World\nGood Bye\nok\n" 3 38 RightParen 3 39 Semicolon 4 1 Keyword_print 4 6 LeftParen 4 7 String "Print a slash n - \\n.\n" 4 33 RightParen 4 34 Semicolon 5 1 End_of_input Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Syntax Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#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-stream) ((stream :type stream :initarg :stream :reader stream-of) (line :type fixnum :initform 1 :accessor line-of) (column :type fixnum :initform 0 :accessor column-of) (prev-column :type (or null fixnum) :initform nil :accessor prev-column-of)) (:documentation "Character input stream that counts lines and columns."))   (defmethod stream-read-char ((stream counting-character-input-stream)) (let ((ch (read-char (stream-of stream) nil :eof))) (case ch (#\Newline (incf (line-of stream)) (setf (prev-column-of stream) (column-of stream) (column-of stream) 0)) (t (incf (column-of stream)))) ch))   (defmethod stream-unread-char ((stream counting-character-input-stream) char) (unread-char char (stream-of stream)) (case char (#\Newline (decf (line-of stream)) (setf (column-of stream) (prev-column-of stream))) (t (decf (column-of stream)))))   (defstruct token (name nil :type symbol) (value nil :type t) (line nil :type fixnum) (column nil :type fixnum))   (defun lexer-error (format-control &rest args) (apply #'error format-control args))   (defun handle-divide-or-comment (stream char) (declare (ignore char)) (case (peek-char nil stream t nil t) (#\* (loop with may-end = nil initially (read-char stream t nil t) for ch = (read-char stream t nil t) until (and may-end (char= ch #\/)) do (setf may-end (char= ch #\*)) finally (return (read stream t nil t)))) (t (make-token :name :op-divide :line (line-of stream) :column (column-of stream)))))   (defun make-constant-handler (token-name) (lambda (stream char) (declare (ignore char)) (make-token :name token-name :line (line-of stream) :column (column-of stream))))   (defun make-this-or-that-handler (expect then &optional else) (lambda (stream char) (declare (ignore char)) (let ((line (line-of stream)) (column (column-of stream)) (next (peek-char nil stream nil nil t))) (cond ((and expect (char= next expect)) (read-char stream nil nil t) (make-token :name then :line line :column column)) (else (make-token :name else :line line :column column)) (t (lexer-error "Unrecognized character '~A'" next))))))   (defun identifier? (symbol) (and (symbolp symbol) (not (keywordp symbol)) (let ((name (symbol-name symbol))) (and (find (char name 0) "_abcdefghijklmnopqrstuvwxyz" :test #'char-equal) (or (< (length name) 2) (not (find-if-not (lambda (ch) (find ch "_abcdefghijklmnopqrstuvwxyz0123456789" :test #'char-equal)) name :start 1)))))))   (defun id->keyword (id line column) (case id (lex-symbols::|if| (make-token :name :keyword-if :line line :column column)) (lex-symbols::|else| (make-token :name :keyword-else :line line :column column)) (lex-symbols::|while| (make-token :name :keyword-while :line line :column column)) (lex-symbols::|print| (make-token :name :keyword-print :line line :column column)) (lex-symbols::|putc| (make-token :name :keyword-putc :line line :column column)) (t nil)))   (defun handle-identifier (stream char) (let ((*readtable* (copy-readtable))) (set-syntax-from-char char #\z) (let ((line (line-of stream)) (column (column-of stream))) (unread-char char stream) (let ((obj (read stream t nil t))) (if (identifier? obj) (or (id->keyword obj line column) (make-token :name :identifier :value obj :line line :column column)) (lexer-error "Invalid identifier name: ~A" obj))))))   (defun handle-integer (stream char) (let ((*readtable* (copy-readtable))) (set-syntax-from-char char #\z) (let ((line (line-of stream)) (column (column-of stream))) (unread-char char stream) (let ((obj (read stream t nil t))) (if (integerp obj) (make-token :name :integer :value obj :line line :column column) (lexer-error "Invalid integer: ~A" obj))))))   (defun handle-char-literal (stream char) (declare (ignore char)) (let* ((line (line-of stream)) (column (column-of stream)) (ch (read-char stream t nil t)) (parsed (case ch (#\' (lexer-error "Empty character constant")) (#\Newline (lexer-error "New line in character literal")) (#\\ (let ((next-ch (read-char stream t nil t))) (case next-ch (#\n #\Newline) (#\\ #\\) (t (lexer-error "Unknown escape sequence: \\~A" next-ch))))) (t ch)))) (if (char= #\' (read-char stream t nil t)) (make-token :name :integer :value (char-code parsed) :line line :column column) (lexer-error "Only one character is allowed in character literal"))))   (defun handle-string (stream char) (declare (ignore char)) (loop with result = (make-array 0 :element-type 'character :adjustable t :fill-pointer t) with line = (line-of stream) with column = (column-of stream) for ch = (read-char stream t nil t) until (char= ch #\") do (setf ch (case ch (#\Newline (lexer-error "New line in string")) (#\\ (let ((next-ch (read-char stream t nil t))) (case next-ch (#\n #\Newline) (#\\ #\\) (t (lexer-error "Unknown escape sequence: \\~A" next-ch))))) (t ch))) (vector-push-extend ch result) finally (return (make-token :name :string :value result :line line :column column))))   (defun make-lexer-readtable () (let ((*readtable* (copy-readtable nil))) (setf (readtable-case *readtable*) :preserve) (set-syntax-from-char #\\ #\z) (set-syntax-from-char #\# #\z) (set-syntax-from-char #\` #\z)    ;; operators (set-macro-character #\* (make-constant-handler :op-multiply)) (set-macro-character #\/ #'handle-divide-or-comment) (set-macro-character #\% (make-constant-handler :op-mod)) (set-macro-character #\+ (make-constant-handler :op-add)) (set-macro-character #\- (make-constant-handler :op-subtract)) (set-macro-character #\< (make-this-or-that-handler #\= :op-lessequal :op-less)) (set-macro-character #\> (make-this-or-that-handler #\= :op-greaterequal :op-greater)) (set-macro-character #\= (make-this-or-that-handler #\= :op-equal :op-assign)) (set-macro-character #\! (make-this-or-that-handler #\= :op-notequal :op-not)) (set-macro-character #\& (make-this-or-that-handler #\& :op-and)) (set-macro-character #\| (make-this-or-that-handler #\| :op-or))    ;; symbols (set-macro-character #\( (make-constant-handler :leftparen)) (set-macro-character #\) (make-constant-handler :rightparen)) (set-macro-character #\{ (make-constant-handler :leftbrace)) (set-macro-character #\} (make-constant-handler :rightbrace)) (set-macro-character #\; (make-constant-handler :semicolon)) (set-macro-character #\, (make-constant-handler :comma))    ;; identifiers & keywords (set-macro-character #\_ #'handle-identifier t) (loop for ch across "abcdefghijklmnopqrstuvwxyz" do (set-macro-character ch #'handle-identifier t)) (loop for ch across "ABCDEFGHIJKLMNOPQRSTUVWXYZ" do (set-macro-character ch #'handle-identifier t))    ;; integers (loop for ch across "0123456789" do (set-macro-character ch #'handle-integer t)) (set-macro-character #\' #'handle-char-literal)    ;; strings (set-macro-character #\" #'handle-string)   *readtable*))   (defun lex (stream) (loop with *readtable* = (make-lexer-readtable) with *package* = +lex-symbols-package+ with eof = (gensym) with counting-stream = (make-instance 'counting-character-input-stream :stream stream) for token = (read counting-stream nil eof) until (eq token eof) do (format t "~5D ~5D ~15A~@[ ~S~]~%" (token-line token) (token-column token) (token-name token) (token-value token)) finally (format t "~5D ~5D ~15A~%" (line-of counting-stream) (column-of counting-stream) :end-of-input) (close counting-stream)))   (defun main () (lex *standard-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, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#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_mem) instead of decode(). -- -- A quick test (calculating fib(44) 10^6 times) suggests ~500 times faster than interp.exw - -- which is to be expected given that a single add instruction (1 clock) here is implemented as -- at least three (and quite possibly five!) resursive calls to interp() in the other. format PE32 --format ELF32 -- Note: cgen generates 32-bit machine code, which cannot be executed directly from a 64-bit interpreter. -- You can however, via the magic of either the above format directives, use a 64-bit version of -- Phix to compile this (just add a -c command line option) to a 32-bit executable, which can. -- It would not be particularly difficult to emit 32 or 64 bit code, but some source code files -- would, fairly obviously, then be very nearly twice as long, and a fair bit harder to read. without js -- (machine code!) include cgen.e procedure main(sequence cl) open_files(cl) toks = lex() object t = parse() code_gen(t) fixup() if machine_bits()=32 then -- ^ as per note above call(code_mem) end if free({var_mem,code_mem}) close_files() end procedure --main(command_line()) main({0,0,"count.c"})
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 Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#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(sequence inode) if inode[1]!=tk_Identifier then ?9/0 end if string ident = inode[2] integer n = find(ident,vars) if n=0 then vars = append(vars,ident) n = length(vars) end if return n end function function string_idx(sequence inode) if inode[1]!=tk_String then ?9/0 end if string s = inode[2] integer n = find(s,strings) if n=0 then strings = append(strings,s) stringptrs = append(stringptrs,0) n = length(strings) end if return n end function function gen_size(object t) -- note: must be kept precisely in sync with gen_rec! -- (relentlessly tested via estsize/actsize) integer size = 0 if t!=NULL then integer n_type = t[1] string node_type = tkNames[n_type] switch n_type do case tk_Sequence: size += gen_size(t[2]) size += gen_size(t[3]) case tk_assign: size += gen_size(t[3])+6 case tk_Integer: size += 5 case tk_Identifier: size += 6 case tk_String: size += 5 case tk_while: -- emit: @@:<condition><topjmp(@f)><body><tailjmp(@b)>@@: size += gen_size(t[2])+3 integer body = gen_size(t[3]) integer stail = iff(size+body+2>128?5:2) integer stop = iff(body+stail >127?6:2) size += stop+body+stail case tk_lt: case tk_le: case tk_ne: case tk_eq: case tk_gt: case tk_ge: size += gen_size(t[2]) size += gen_size(t[3]) size += 10 case tk_and: case tk_or: size += gen_size(t[2]) size += gen_size(t[3]) size += 15 case tk_add: case tk_sub: size += gen_size(t[2]) size += gen_size(t[3]) size += 4 case tk_mul: size += gen_size(t[2]) size += gen_size(t[3]) size += 5 case tk_div: case tk_mod: size += gen_size(t[2]) size += gen_size(t[3]) size += 6 case tk_putc: case tk_Printi: case tk_Prints: size += gen_size(t[2]) size += 5 case tk_if: size += gen_size(t[2])+3 if t[3][1]!=tk_if then ?9/0 end if integer truesize = gen_size(t[3][2]) integer falsesize = gen_size(t[3][3]) integer elsejmp = iff(falsesize=0?0:iff(falsesize>127?5:2)) integer mainjmp = iff(truesize+elsejmp>127?6:2) size += mainjmp+truesize+elsejmp+falsesize case tk_not: size += gen_size(t[2]) size += 9 case tk_neg: size += gen_size(t[2]) size += 4 else: ?9/0 end switch end if return size end function procedure gen_rec(object t) -- the recursive part of code_gen if t!=NULL then integer initsize = length(code) integer estsize = gen_size(t) -- (test the gen_size function) integer n_type = t[1] string node_type = tkNames[n_type] switch n_type do case tk_Sequence: gen_rec(t[2]) gen_rec(t[3]) case tk_assign: integer n = var_idx(t[2]) gen_rec(t[3]) code &= {0o217,0o005,chain,1,n,0} -- pop [i] chain = length(code)-3 case tk_Integer: integer n = t[2] code &= 0o150&int_to_bytes(n) -- push imm32 case tk_while: -- emit: @@:<condition><topjmp(@f)><body><tailjmp(@b)>@@: integer looptop = length(code) gen_rec(t[2]) code &= {0o130, -- pop eax 0o205,0o300} -- test eax,eax integer bodysize = gen_size(t[3]) -- can we use short jumps? -- disclaimer: size calcs are not heavily tested; if in -- doubt reduce 128/7 by 8, and if that works -- then yep, you just found a boundary case. integer stail = iff(length(code)+bodysize+4-looptop>128?5:2) integer offset = bodysize+stail integer stop = iff(offset>127?6:2) if stop=2 then code &= {0o164,offset} -- jz (short) end else code &= {0o017,0o204}&int_to_bytes(offset) -- jz (long) end end if gen_rec(t[3]) offset = looptop-(length(code)+stail) if stail=2 then code &= 0o353&offset -- jmp looptop (short) else code &= 0o351&int_to_bytes(offset) -- jmp looptop (long) end if case tk_lt: case tk_le: case tk_gt: case tk_ge: case tk_ne: case tk_eq: gen_rec(t[2]) gen_rec(t[3]) integer xrm if n_type=tk_ne then xrm = 0o225 -- (#95) elsif n_type=tk_lt then xrm = 0o234 -- (#9C) elsif n_type=tk_ge then xrm = 0o235 -- (#9D) elsif n_type=tk_le then xrm = 0o236 -- (#9E) elsif n_type=tk_gt then xrm = 0o237 -- (#9F) else ?9/0 end if code &= { 0o061,0o300, -- xor eax,eax 0o132, -- pop edx 0o131, -- pop ecx 0o071,0o321, -- cmp ecx,edx 0o017,xrm,0o300, -- setcc al 0o120} -- push eax case tk_or: case tk_and: gen_rec(t[2]) gen_rec(t[3]) integer op = find(n_type,{tk_or,0,0,tk_and}) op *= 0o010 code &= { 0o130, -- pop eax 0o131, -- pop ecx 0o205,0o300, -- test eax,eax 0o017,0o225,0o300, -- setne al 0o205,0o311, -- test ecx,ecx 0o017,0o225,0o301, -- setne cl op,0o310, -- or/and al,cl 0o120} -- push eax case tk_add: case tk_sub: gen_rec(t[2]) gen_rec(t[3]) integer op = find(n_type,{tk_add,0,0,0,0,tk_sub}) op = 0o001 + (op-1)*0o010 code &= { 0o130, -- pop eax op,0o004,0o044} -- add/or/and/sub [esp],eax case tk_mul: gen_rec(t[2]) gen_rec(t[3]) code &= { 0o131, -- pop ecx 0o130, -- pop eax 0o367,0o341, -- mul ecx 0o120} -- push eax case tk_div: case tk_mod: gen_rec(t[2]) gen_rec(t[3]) integer push = 0o120+(n_type=tk_mod)*2 code &= { 0o131, -- pop ecx 0o130, -- pop eax 0o231, -- cdq (eax -> edx:eax) 0o367,0o371, -- idiv ecx push} -- push eax|edx case tk_Identifier: integer n = var_idx(t) code &= {0o377,0o065,chain,1,n,0} -- push [n] chain = length(code)-3 case tk_putc: case tk_Printi: case tk_Prints: gen_rec(t[2]) integer n = find(n_type,{tk_putc,tk_Printi,tk_Prints}) code &= {0o350,chain,3,n,0} -- call :printc/i/s chain = length(code)-3 case tk_String: integer n = string_idx(t) code &= {0o150,chain,2,n,0} -- push RawStringPtr(string) chain = length(code)-3 case tk_if: -- emit: <condition><mainjmp><truepart>[<elsejmp><falsepart>] gen_rec(t[2]) code &= {0o130, -- pop eax 0o205,0o300} -- test eax,eax if t[3][1]!=tk_if then ?9/0 end if integer truesize = gen_size(t[3][2]) integer falsesize = gen_size(t[3][3]) integer elsejmp = iff(falsesize=0?0:iff(falsesize>127?5:2)) integer offset = truesize+elsejmp integer mainjmp = iff(offset>127?6:2) if mainjmp=2 then code &= {0o164,offset} -- jz (short) else/end else code &= {0o017,0o204}&int_to_bytes(offset) -- jz (long) else/end end if gen_rec(t[3][2]) if falsesize!=0 then offset = falsesize if elsejmp=2 then code &= 0o353&offset -- jmp end if (short) else code &= 0o351&int_to_bytes(offset) -- jmp end if (long) end if gen_rec(t[3][3]) end if case tk_not: gen_rec(t[2]) code &= {0o132, -- pop edx 0o061,0o300, -- xor eax,eax 0o205,0o322, -- test edx,edx 0o017,0o224,0o300, -- setz al 0o120} -- push eax case tk_neg: gen_rec(t[2]) code &= {0o130, -- pop eax 0o367,0o330, -- neg eax 0o120} -- push eax else: error("error in code generator - found %d, expecting operator\n", {n_type}) end switch integer actsize = length(code) if initsize+estsize!=actsize then ?"9/0" end if -- (test gen_size) end if end procedure global procedure code_gen(object t) -- -- Generates proper machine code. -- -- Example: i=10; print "\n"; print i; print "\n" -- Result in vars, strings, chain, code (declared above) -- where vars is: {"i"}, -- strings is {"\n"}, -- code is { 0o150,#0A,#00,#00,#00, -- 1: push 10 -- 0o217,0o005,0,1,1,0 -- 6: pop [i] -- 0o150,8,2,1,0, -- 12: push ("\n") -- 0o350,13,3,3,0, -- 17: call :prints -- 0o377,0o065,18,1,1,0, -- 22: push [i] -- 0o350,24,3,2,0, -- 28: call :printi -- 0o150,29,2,1,0, -- 33: push ("\n") -- 0o350,34,3,3,0, -- 38: call :prints -- 0o303} -- 43: ret -- and chain is 39 (->34->29->24->18->13->8->0) -- The chain connects all places where we need an actual address before -- the code is executed, with the byte after the link differentiating -- between var(1), string(2), and builtin(3), and the byte after that -- determining the instance of the given type - not that any of them -- are actually limited to a byte in the above intermediate form, and -- of course the trailing 0 of each {link,type,id,0} is just there to -- reserve the space we will need. -- gen_rec(t) code = append(code,0o303) -- ret (0o303=#C3) end procedure include builtins/VM/puts1.e -- low-level console i/o routines function setbuiltins() atom printc,printi,prints #ilASM{ jmp :setbuiltins  ::printc lea edi,[esp+4] mov esi,1 call :%puts1ediesi -- (edi=raw text, esi=length) ret 4  ::printi mov eax,[esp+4] push 0 -- no cr call :%putsint -- (nb limited to +/-9,999,999,999) ret 4  ::prints mov edi,[esp+4] mov esi,[edi-12] call :%puts1ediesi -- (edi=raw text, esi=length) ret 4  ::setbuiltins mov eax,:printc lea edi,[printc] call :%pStoreMint mov eax,:printi lea edi,[printi] call :%pStoreMint mov eax,:prints lea edi,[prints] call :%pStoreMint } return {printc,printi,prints} end function global constant builtin_names = {"printc","printi","prints"} global constant builtins = setbuiltins() global atom var_mem, code_mem function RawStringPtr(integer n) -- (based on IupRawStringPtr from pGUI.e) -- -- Returns a raw string pointer for s, somewhat like allocate_string(s), but using the existing memory. -- NOTE: The return is only valid as long as the value passed as the parameter remains in existence. -- atom res string s = strings[n] #ilASM{ mov eax,[s] lea edi,[res] shl eax,2 call :%pStoreMint } stringptrs[n] = res return res end function global procedure fixup() var_mem = allocate(length(vars)*4) mem_set(var_mem,0,length(vars)*4) code_mem = allocate(length(code)) poke(code_mem,code) while chain!=0 do integer this = chain chain = code[this] integer ftype = code[this+1] integer id = code[this+2] switch ftype do case 1: -- vars poke4(code_mem+this-1,var_mem+(id-1)*4) case 2: -- strings poke4(code_mem+this-1,RawStringPtr(id)) case 3: -- builtins poke4(code_mem+this-1,builtins[id]-(code_mem+this+3)) end switch end while end procedure
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Measure a relative performance of sorting algorithms implementations. Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures). Consider three type of input sequences:   ones: sequence of all 1's.   Example: {1, 1, 1, 1, 1}   range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}   shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8} Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm). For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations. Preliminary subtask:   Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort   Query Performance   Write float arrays to a text file   Plot x, y arrays   Polynomial Fitting General steps:   Define sorting routines to be considered.   Define appropriate sequence generators and write timings.   Plot timings.   What conclusions about relative performance of the sorting routines could be made based on the plots?
#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| var seq = shuffledSeq.call(n) seq.sort() return seq }   var bubbleSort = Fn.new { |a| var n = a.count while (true) { var n2 = 0 for (i in 1...n) { if (a[i - 1] > a[i]) { a.swap(i, i - 1) n2 = i } } n = n2 if (n == 0) break } }   // counting sort of 'a' according to the digit represented by 'exp' var countSort = Fn.new { |a, exp| var n = a.count var output = [0] * n var count = [0] * 10 for (i in 0...n) { var t = (a[i]/exp).truncate % 10 count[t] = count[t] + 1 } for (i in 1..9) count[i] = count[i] + count[i-1] for (i in n-1..0) { var t = (a[i]/exp).truncate % 10 output[count[t] - 1] = a[i] count[t] = count[t] - 1 } for (i in 0...n) a[i] = output[i] }   // sorts 'a' in place var radixSort = Fn.new { |a| // check for negative elements var min = a.reduce { |m, i| (i < m) ? i : m } // if there are any, increase all elements by -min if (min < 0) (0...a.count).each { |i| a[i] = a[i] - min } // now get the maximum to know number of digits var max = a.reduce { |m, i| (i > m) ? i : m } // do counting sort for each digit var exp = 1 while ((max/exp).truncate > 0) { countSort.call(a, exp) exp = exp * 10 } // if there were negative elements, reduce all elements by -min if (min < 0) (0...a.count).each { |i| a[i] = a[i] + min } }   var measureTime = Fn.new { |sort, seq| var start = System.clock sort.call(seq) return ((System.clock - start) * 1e6).round // microseconds }   var runs = 10 var lengths = [1, 10, 100, 1000, 10000, 50000] var sorts = [ bubbleSort, Fn.new { |a| Sort.insertion(a) }, Fn.new { |a| Sort.quick(a) }, radixSort, Fn.new { |a| Sort.shell(a) } ]   var sortTitles = ["Bubble", "Insert", "Quick ", "Radix ", "Shell "] var seqTitles = ["All Ones", "Ascending", "Shuffled"] var totals = List.filled(seqTitles.count, null) for (i in 0...totals.count) { totals[i] = List.filled(sorts.count, null) for (j in 0...sorts.count) totals[i][j] = List.filled(lengths.count, 0) } var k = 0 for (n in lengths) { var seqs = [onesSeq.call(n), ascendingSeq.call(n), shuffledSeq.call(n)] for (r in 0...runs) { for (i in 0...seqs.count) { for (j in 0...sorts.count) { var seq = seqs[i].toList totals[i][j][k] = totals[i][j][k] + measureTime.call(sorts[j], seq) } } } k = k + 1 } System.print("All timings in microseconds\n") System.write("Sequence length") for (len in lengths) Fmt.write("$8d ", len) System.print("\n") for (i in 0...seqTitles.count) { System.print("  %(seqTitles[i]):") for (j in 0...sorts.count) { System.write("  %(sortTitles[j]) ") for (k in 0...lengths.count) { var time = (totals[i][j][k] / runs).round Fmt.write("$8d ", time) } System.print() } System.print("\n") }
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 | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a parser module/library/class, it would be great if two versions of the solution are provided: One without the parser module, and one with. Grammar The simple programming language to be analyzed is more or less a (very tiny) subset of C. The formal grammar in Extended Backus-Naur Form (EBNF):   stmt_list = {stmt} ;   stmt = ';' | Identifier '=' expr ';' | 'while' paren_expr stmt | 'if' paren_expr stmt ['else' stmt] | 'print' '(' prt_list ')' ';' | 'putc' paren_expr ';' | '{' stmt_list '}'  ;   paren_expr = '(' expr ')' ;   prt_list = (string | expr) {',' (String | expr)} ;   expr = and_expr {'||' and_expr} ; and_expr = equality_expr {'&&' equality_expr} ; equality_expr = relational_expr [('==' | '!=') relational_expr] ; relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ; addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ; multiplication_expr = primary {('*' | '/' | '%') primary } ; primary = Identifier | Integer | '(' expr ')' | ('+' | '-' | '!') primary  ; The resulting AST should be formulated as a Binary Tree. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast The following table shows the input to lex, lex output, and the AST produced by the parser Input to lex Output from lex, input to parse Output from parse count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Specifications List of node type names Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or In the text below, Null/Empty nodes are represented by ";". Non-terminal (internal) nodes For Operators, the following nodes should be created: Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or For each of the above nodes, the left and right sub-nodes are the operands of the respective operation. In pseudo S-Expression format: (Operator expression expression) Negate, Not For these node types, the left node is the operand, and the right node is null. (Operator expression ;) Sequence - sub-nodes are either statements or Sequences. If - left node is the expression, the right node is If node, with it's left node being the if-true statement part, and the right node being the if-false (else) statement part. (If expression (If statement else-statement)) If there is not an else, the tree becomes: (If expression (If statement ;)) Prtc (Prtc (expression) ;) Prts (Prts (String "the string") ;) Prti (Prti (Integer 12345) ;) While - left node is the expression, the right node is the statement. (While expression statement) Assign - left node is the left-hand side of the assignment, the right node is the right-hand side of the assignment. (Assign Identifier expression) Terminal (leaf) nodes: Identifier: (Identifier ident_name) Integer: (Integer 12345) String: (String "Hello World!") ";": Empty node Some simple examples Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path. This simple program: a=11; Produces the following AST, encoded as a binary tree: Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node: (1) Sequence (2) |-- ; (3) |-- Assign (4) |-- Identifier: a (5) |-- Integer: 11 In flattened form: (1) Sequence (2) ; (3) Assign (4) Identifier a (5) Integer 11 This program: a=11; b=22; c=33; Produces the following AST: ( 1) Sequence ( 2) |-- Sequence ( 3) | |-- Sequence ( 4) | | |-- ; ( 5) | | |-- Assign ( 6) | | |-- Identifier: a ( 7) | | |-- Integer: 11 ( 8) | |-- Assign ( 9) | |-- Identifier: b (10) | |-- Integer: 22 (11) |-- Assign (12) |-- Identifier: c (13) |-- Integer: 33 In flattened form: ( 1) Sequence ( 2) Sequence ( 3) Sequence ( 4) ; ( 5) Assign ( 6) Identifier a ( 7) Integer 11 ( 8) Assign ( 9) Identifier b (10) Integer 22 (11) Assign (12) Identifier c (13) Integer 33 Pseudo-code for the parser. Uses Precedence Climbing for expression parsing, and Recursive Descent for statement parsing. The AST is also built: def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error()   while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q))   return x   def paren_expr() expect("(") x = expr(0) expect(")") return x   def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0))   t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t   def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t Once the AST is built, it should be output in a flattened format. This can be as simple as the following def prt_ast(t) if t == NULL print(";\n") else print(t.node_type) if t.node_type in [Identifier, Integer, String] # leaf node print the value of the Ident, Integer or String, "\n" else print("\n") prt_ast(t.left) prt_ast(t.right) If the AST is correctly built, loading it into a subsequent program should be as simple as def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) Finally, the AST can also be tested by running it against one of the AST Interpreter solutions. Test program, assuming this is in a file called prime.t lex <prime.t | parse Input to lex Output from lex, input to parse Output from parse /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 4 1 Identifier count 4 7 Op_assign 4 9 Integer 1 4 10 Semicolon 5 1 Identifier n 5 3 Op_assign 5 5 Integer 1 5 6 Semicolon 6 1 Identifier limit 6 7 Op_assign 6 9 Integer 100 6 12 Semicolon 7 1 Keyword_while 7 7 LeftParen 7 8 Identifier n 7 10 Op_less 7 12 Identifier limit 7 17 RightParen 7 19 LeftBrace 8 5 Identifier k 8 6 Op_assign 8 7 Integer 3 8 8 Semicolon 9 5 Identifier p 9 6 Op_assign 9 7 Integer 1 9 8 Semicolon 10 5 Identifier n 10 6 Op_assign 10 7 Identifier n 10 8 Op_add 10 9 Integer 2 10 10 Semicolon 11 5 Keyword_while 11 11 LeftParen 11 12 LeftParen 11 13 Identifier k 11 14 Op_multiply 11 15 Identifier k 11 16 Op_lessequal 11 18 Identifier n 11 19 RightParen 11 21 Op_and 11 24 LeftParen 11 25 Identifier p 11 26 RightParen 11 27 RightParen 11 29 LeftBrace 12 9 Identifier p 12 10 Op_assign 12 11 Identifier n 12 12 Op_divide 12 13 Identifier k 12 14 Op_multiply 12 15 Identifier k 12 16 Op_notequal 12 18 Identifier n 12 19 Semicolon 13 9 Identifier k 13 10 Op_assign 13 11 Identifier k 13 12 Op_add 13 13 Integer 2 13 14 Semicolon 14 5 RightBrace 15 5 Keyword_if 15 8 LeftParen 15 9 Identifier p 15 10 RightParen 15 12 LeftBrace 16 9 Keyword_print 16 14 LeftParen 16 15 Identifier n 16 16 Comma 16 18 String " is prime\n" 16 31 RightParen 16 32 Semicolon 17 9 Identifier count 17 15 Op_assign 17 17 Identifier count 17 23 Op_add 17 25 Integer 1 17 26 Semicolon 18 5 RightBrace 19 1 RightBrace 20 1 Keyword_print 20 6 LeftParen 20 7 String "Total primes found: " 20 29 Comma 20 31 Identifier count 20 36 Comma 20 38 String "\n" 20 42 RightParen 20 43 Semicolon 21 1 End_of_input Sequence Sequence Sequence Sequence Sequence ; Assign Identifier count Integer 1 Assign Identifier n Integer 1 Assign Identifier limit Integer 100 While Less Identifier n Identifier limit Sequence Sequence Sequence Sequence Sequence ; Assign Identifier k Integer 3 Assign Identifier p Integer 1 Assign Identifier n Add Identifier n Integer 2 While And LessEqual Multiply Identifier k Identifier k Identifier n Identifier p Sequence Sequence ; Assign Identifier p NotEqual Multiply Divide Identifier n Identifier k Identifier k Identifier n Assign Identifier k Add Identifier k Integer 2 If Identifier p If Sequence Sequence ; Sequence Sequence ; Prti Identifier n ; Prts String " is prime\n" ; Assign Identifier count Add Identifier count Integer 1 ; Sequence Sequence Sequence ; Prts String "Total primes found: " ; Prti Identifier count ; Prts String "\n" ; Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#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) (cons 'Op_not 'Not) (cons 'Op_equal 'Equal) (cons 'Op_notequal 'NotEqual) (cons 'Op_or 'Or) (cons 'Op_and 'And) (cons 'Op_less 'Less) (cons 'Op_lessequal 'LessEqual) (cons 'Op_greater 'Greater) (cons 'Op_greaterequal 'GreaterEqual)))   (define (retrieve-name type) (let ((res (assq type *names*))) (if res (cdr res) (error "Unknown type name"))))   ;; takes a vector of tokens (define (parse tokens) ; read statements, until hit end of tokens (define posn 0) (define (peek-token) (vector-ref tokens posn)) (define (get-token) (set! posn (+ 1 posn)) (vector-ref tokens (- posn 1))) (define (match type) (if (eq? (car (vector-ref tokens posn)) type) (set! posn (+ 1 posn)) (error "Could not match token type" type))) ; make it easier to read token parts (define type car) (define value cadr) ; ;; left associative read of one or more items with given separators (define (read-one-or-more reader separators) (let loop ((lft (reader))) (let ((next (peek-token))) (if (memq (type next) separators) (begin (match (type next)) (loop (list (retrieve-name (type next)) lft (reader)))) lft)))) ; ;; read one or two items with given separator (define (read-one-or-two reader separators) (let* ((lft (reader)) (next (peek-token))) (if (memq (type next) separators) (begin (match (type next)) (list (retrieve-name (type next)) lft (reader))) lft))) ; (define (read-primary) (let ((next (get-token))) (case (type next) ((Identifier Integer) next) ((LeftParen) (let ((v (read-expr))) (match 'RightParen) v)) ((Op_add) ; + sign is ignored (read-primary)) ((Op_not) (list 'Not (read-primary) '())) ((Op_subtract) (list 'Negate (read-primary) '())) (else (error "Unknown primary type"))))) ; (define (read-multiplication-expr) ; * (read-one-or-more read-primary '(Op_multiply Op_divide Op_mod))) ; (define (read-addition-expr) ; * (read-one-or-more read-multiplication-expr '(Op_add Op_subtract))) ; (define (read-relational-expr) ; ? (read-one-or-two read-addition-expr '(Op_less Op_lessequal Op_greater Op_greaterequal))) ; (define (read-equality-expr) ; ? (read-one-or-two read-relational-expr '(Op_equal Op_notequal))) ; (define (read-and-expr) ; * (read-one-or-more read-equality-expr '(Op_and))) ; (define (read-expr) ; * (read-one-or-more read-and-expr '(Op_or))) ; (define (read-prt-list) (define (read-print-part) (if (eq? (type (peek-token)) 'String) (list 'Prts (get-token) '()) (list 'Prti (read-expr) '()))) ; (do ((tok (read-print-part) (read-print-part)) (rec '() (list 'Sequence rec tok))) ((not (eq? (type (peek-token)) 'Comma)) (list 'Sequence rec tok)) (match 'Comma))) ; (define (read-paren-expr) (match 'LeftParen) (let ((v (read-expr))) (match 'RightParen) v)) ; (define (read-stmt) (case (type (peek-token)) ((SemiColon) '()) ((Identifier) (let ((id (get-token))) (match 'Op_assign) (let ((ex (read-expr))) (match 'Semicolon) (list 'Assign id ex)))) ((Keyword_while) (match 'Keyword_while) (let* ((expr (read-paren-expr)) (stmt (read-stmt))) (list 'While expr stmt))) ((Keyword_if) (match 'Keyword_if) (let* ((expr (read-paren-expr)) (then-part (read-stmt)) (else-part (if (eq? (type (peek-token)) 'Keyword_else) (begin (match 'Keyword_else) (read-stmt)) '()))) (list 'If expr (list 'If then-part else-part)))) ((Keyword_print) (match 'Keyword_print) (match 'LeftParen) (let ((v (read-prt-list))) (match 'RightParen) (match 'Semicolon) v)) ((Keyword_putc) (match 'Keyword_putc) (let ((v (read-paren-expr))) (match 'Semicolon) (list 'Putc v '()))) ((LeftBrace) (match 'LeftBrace) (let ((v (read-stmts))) (match 'RightBrace) v)) (else (error "Unknown token type for statement" (type (peek-token)))))) ; (define (read-stmts) (do ((sequence (list 'Sequence '() (read-stmt)) (list 'Sequence sequence (read-stmt)))) ((memq (type (peek-token)) '(End_of_input RightBrace)) sequence))) ; (let ((res (read-stmts))) (match 'End_of_input) res))   ;; reads tokens from file, parses and returns the AST (define (parse-file filename) (define (tokenise line) (let ((port (open-input-string line))) (read port) ; discard line (read port) ; discard col (let* ((type (read port)) ; read type as symbol (val (read port))) ; check for optional value (if (eof-object? val) (list type) (list type val))))) ; (with-input-from-file filename (lambda () (do ((line (read-line) (read-line)) (toks '() (cons (tokenise line) toks))) ((eof-object? line) (parse (list->vector (reverse toks))))))))   ;; Output the AST in flattened format (define (display-ast ast) (cond ((null? ast) (display ";\n")) ((= 2 (length ast)) (display (car ast)) (display #\tab) (write (cadr ast)) ; use write to preserve " " on String (newline)) (else (display (car ast)) (newline) (display-ast (cadr ast)) (display-ast (cadr (cdr ast))))))   ;; read from filename passed on command line (if (= 2 (length (command-line))) (display-ast (parse-file (cadr (command-line)))) (display "Error: provide program filename\n"))  
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)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#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"; background = lightBlue; borderStyle = sizable; hasMaximize = true; hasMinimize = true; hasClose = true; clientSize = { width * cellWidth, height * cellHeight };   Timer tickTimer { delay = 0.05, started = true, userData = this;   bool DelayExpired() { int y, x, ix = 0; for(y = 0; y < height; y++) { for(x = 0; x < width; x++, ix++) { int nCount = 0; byte alive; if(x > 0 && y > 0 && grid[ix - width - 1]) nCount++; if( y > 0 && grid[ix - width ]) nCount++; if(x < width-1 && y > 0 && grid[ix - width + 1]) nCount++; if(x > 0 && grid[ix - 1]) nCount++; if(x < width - 1 && grid[ix + 1]) nCount++; if(x > 0 && y < height-1 && grid[ix + width - 1]) nCount++; if( y < height-1 && grid[ix + width ]) nCount++; if(x < width-1 && y < height-1 && grid[ix + width + 1]) nCount++;   if(grid[ix]) alive = nCount >= 2 && nCount <= 3; // Death else alive = nCount == 3; // Birth newState[ix] = alive; } } memcpy(grid.array, newState.array, width * height); Update(null); return true; } };   void OnRedraw(Surface surface) { int x, y; int ix = 0;   surface.background = navy; for(y = 0; y < height; y++) { for(x = 0; x < width; x++, ix++) { if(grid[ix]) { int sy = y * cellHeight; int sx = x * cellWidth; surface.Area(sx, sy, sx + cellWidth-1, sy + cellHeight-1); } } } }   bool OnCreate() { int i;   RandomSeed(seed);   for(i = 0; i < popInit; i++) { int x = GetRandom(0, width-1); int y = GetRandom(0, height-1);   grid[y * width + x] = 1; } return true; } }   GameOfLife life {};  
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 See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Sidef
Sidef
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 if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#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 instruction : don’t skip next instruction.
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 programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   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 of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#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.length) { val m = Pattern.compile("([1-9][0-9]*)").matcher(s.substring(start)) val result = new StringBuffer(s.substring(0, start)) if (m.find) { val sb = new StringBuilder(m.group(1)).reverse for (i <- step until sb.length by step) sb.insert(i, ins) m.appendReplacement(result, sb.reverse.toString) } println(m.appendTail(result)) } }   commatize("pi=3.14159265358979323846264338327950288419716939937510582" + "097494459231", 6, 5, " ") commatize("The author has two Z$100000000000000 Zimbabwe notes (100 " + "trillion).", 0, 3, ".")   val sc = new Scanner(new File("input.txt")) while (sc.hasNext) commatize(sc.nextLine) }
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 programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   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 of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#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 = Array(separator) let startIdx = index(startIndex, offsetBy: start) let matches = String.commaReg.matches(in: self, range: NSRange(startIdx..., in: self))   guard !matches.isEmpty else { return self }   let fullMatch = String(self[Range(matches.first!.range(at: 0), in: self)!]) let splits = fullMatch.components(separatedBy: ".") var ip = splits[0]   if ip.count > period { var builder = Array(ip.reversed())   for i in stride(from: (ip.count - 1) / period * period, through: period, by: -period) { builder.insert(contentsOf: sep, at: i) }   ip = String(builder.reversed()) }   if fullMatch.contains(".") { var dp = splits[1]   if dp.count > period { var builder = Array(dp)   for i in stride(from: (dp.count - 1) / period * period, through: period, by: -period) { builder.insert(contentsOf: sep, at: i) }   dp = String(builder) }   ip += "." + dp }   return String(prefix(start)) + String(dropFirst(start)).replacingOccurrences(of: fullMatch, with: ip) } }   let tests = [ "123456789.123456789", ".123456789", "57256.1D-4", "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "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 of the earth is 57268900(29% of the surface) square miles.", "Ain't no numbers in this here words, nohow, no way, Jose.", "James was never known as 0000000007", "Arthur Eddington wrote: I believe there are " + "15747724136275002577605653961181555468044717914527116709366231425076185631031296" + " protons in the universe.", " $-140000±100 millions.", "6/9/1946 was a good year for some." ]   print(tests[0].commatize(period: 2, separator: "*")) print(tests[1].commatize(period: 3, separator: "-")) print(tests[2].commatize(period: 4, separator: "__")) print(tests[3].commatize(period: 5, separator: " ")) print(tests[4].commatize(separator: "."))   for testCase in tests.dropFirst(5) { print(testCase.commatize()) }
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 the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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: strict_ascending([second | rest]) end   lists = [ ~w(AA AA AA AA), ~w(AA ACB BB CC), ~w(AA CC BB), [], ["XYZ"] ] Enum.each(lists, fn list -> IO.puts "#{inspect RC.compare_strings(list)}\t<= #{inspect list} " end)
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 the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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(Strings)) ).  
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. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#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:]=%   for %%x in (%proc%) do ( set /a cont+=1 set x=%%x set str!cont!=!x:"=! ) set /a bef=%cont%-1 set output=%str1% if %cont%==2 (set output=%str1% and %str2%) if %cont% gtr 2 ( for /l %%y in (2,1,%bef%) do ( set output=!output!^, !str%%y! ) set output=!output! and !str%cont%! ) echo {!output!} goto :EOF ::/THE FUNCTION
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 {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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) { string combinationStr = string.Join(" ", combination); Console.WriteLine(combinationStr); }   var donuts = Enumerable.Range(1, 10).ToList();   int donutsCombinationsNumber = GenerateCombinations(donuts, 3).Count;   Console.WriteLine("{0} ways to order 3 donuts given 10 types", donutsCombinationsNumber); }   private static List<List<T>> GenerateCombinations<T>(List<T> combinationList, int k) { var combinations = new List<List<T>>();   if (k == 0) { var emptyCombination = new List<T>(); combinations.Add(emptyCombination);   return combinations; }   if (combinationList.Count == 0) { return combinations; }   T head = combinationList[0]; var copiedCombinationList = new List<T>(combinationList);   List<List<T>> subcombinations = GenerateCombinations(copiedCombinationList, k - 1);   foreach (var subcombination in subcombinations) { subcombination.Insert(0, head); combinations.Add(subcombination); }   combinationList.RemoveAt(0); combinations.AddRange(GenerateCombinations(combinationList, k));   return 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 Permutation. 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) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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 Permutation. 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) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#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 Return (z) End Function   Function CombBig(Byval x As Long, Byval y As Long) As Double If y > x Then Return (0) Elseif x = y Then Return (1) Else If x - y < y Then y = x - y Return (PermBig(x, y) / FactBig(y)) End If End Function   Dim As Long i, j Print "-- Long Integer - Permutations - from 1 to 12" For i = 1 To 12 For j = 1 To i Print "P(" & i & "," & j & ")=" & Str(PermBig(i, j)) & " "; Next j Print "" Next i   Print Chr(10) & "-- Float integer - Combinations from 10 to 60" For i = 10 To 60 Step 10 For j = 1 To i Step i \ 5 Print "C(" & i & "," & j & ")=" & Str(CombBig(i, j)) & " "; Next j Print "" Next i   Print Chr(10) & "-- Float integer - Permutations from 5000 to 15000" For i = 5000 To 15000 Step 5000 For j = 10 To 50 Step 20 Print "P(" & i & "," & j & ")=" & Str(PermBig(i, j)) & " "; Next j Print "" Next i   Print Chr(10) & "-- Float integer - Combinations from 200 to 1000" For i = 200 To 1000 Step 200 For j = 20 To 100 Step 20 Print "C(" & i & "," & j & ")=" & Str(CombBig(i, j)) & " "; Next j Print "" Next i Sleep
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 also used to refer to the first stage of a lexer). Task[edit] Create a lexical analyzer for the simple programming language specified below. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a lexer module/library/class, it would be great if two versions of the solution are provided: One without the lexer module, and one with. Input Specification The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens: Operators Name Common name Character sequence Op_multiply multiply * Op_divide divide / Op_mod mod % Op_add plus + Op_subtract minus - Op_negate unary minus - Op_less less than < Op_lessequal less than or equal <= Op_greater greater than > Op_greaterequal greater than or equal >= Op_equal equal == Op_notequal not equal != Op_not unary not ! Op_assign assignment = Op_and logical and && Op_or logical or ¦¦ The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task. Symbols Name Common name Character LeftParen left parenthesis ( RightParen right parenthesis ) LeftBrace left brace { RightBrace right brace } Semicolon semi-colon ; Comma comma , Keywords Name Character sequence Keyword_if if Keyword_else else Keyword_while while Keyword_print print Keyword_putc putc Identifiers and literals These differ from the the previous tokens, in that each occurrence of them has a value associated with it. Name Common name Format description Format regex Value Identifier identifier one or more letter/number/underscore characters, but not starting with a number [_a-zA-Z][_a-zA-Z0-9]* as is Integer integer literal one or more digits [0-9]+ as is, interpreted as a number Integer char literal exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes '([^'\n]|\\n|\\\\)' the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n' String string literal zero or more characters (anything except newline or double quote), enclosed by double quotes "[^"\n]*" the characters without the double quotes and with escape sequences converted For char and string literals, the \n escape sequence is supported to represent a new-line character. For char and string literals, to represent a backslash, use \\. No other special sequences are supported. This means that: Char literals cannot represent a single quote character (value 39). String literals cannot represent strings containing double quote characters. Zero-width tokens Name Location End_of_input when the end of the input stream is reached White space Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below. "Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =). Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge. This means: keywords, identifiers, and integer literals. e.g. ifprint is recognized as an identifier, instead of the keywords if and print. e.g. 42fred is invalid, and neither recognized as a number nor an identifier. Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value). e.g. & & is invalid, and not interpreted as the && operator. For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions: if ( p /* meaning n is prime */ ) { print ( n , " " ) ; count = count + 1 ; /* number of primes found so far */ } if(p){print(n," ");count=count+1;} Complete list of token names 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_notequal Op_assign Op_and Op_or Keyword_if Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen LeftBrace RightBrace Semicolon Comma Identifier Integer String Output Format The program output should be a sequence of lines, each consisting of the following whitespace-separated fields: the line number where the token starts the column number where the token starts the token name the token value (only for Identifier, Integer, and String tokens) the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement. This task is intended to be used as part of a pipeline, with the other compiler tasks - for example: lex < hello.t | parse | gen | vm Or possibly: lex hello.t lex.out parse lex.out parse.out gen parse.out gen.out vm gen.out This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs. Diagnostics The following error conditions should be caught: Error Example Empty character constant '' Unknown escape sequence. \r Multi-character constant. 'xx' End-of-file in comment. Closing comment characters not found. End-of-file while scanning string literal. Closing string character not found. End-of-line while scanning string literal. Closing string character not found before end-of-line. Unrecognized character. | Invalid number. Starts like a number, but ends in non-numeric characters. 123abc Test Cases Input Output Test Case 1: /* Hello world */ print("Hello, World!\n"); 4 1 Keyword_print 4 6 LeftParen 4 7 String "Hello, World!\n" 4 24 RightParen 4 25 Semicolon 5 1 End_of_input Test Case 2: /* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, "\n"); 4 1 Identifier phoenix_number 4 16 Op_assign 4 18 Integer 142857 4 24 Semicolon 5 1 Keyword_print 5 6 LeftParen 5 7 Identifier phoenix_number 5 21 Comma 5 23 String "\n" 5 27 RightParen 5 28 Semicolon 6 1 End_of_input Test Case 3: /* All lexical tokens - not syntactically correct, but that will have to wait until syntax analysis */ /* Print */ print /* Sub */ - /* Putc */ putc /* Lss */ < /* If */ if /* Gtr */ > /* Else */ else /* Leq */ <= /* While */ while /* Geq */ >= /* Lbrace */ { /* Eq */ == /* Rbrace */ } /* Neq */ != /* Lparen */ ( /* And */ && /* Rparen */ ) /* Or */ || /* Uminus */ - /* Semi */ ; /* Not */ ! /* Comma */ , /* Mul */ * /* Assign */ = /* Div */ / /* Integer */ 42 /* Mod */ % /* String */ "String literal" /* Add */ + /* Ident */ variable_name /* character literal */ '\n' /* character literal */ '\\' /* character literal */ ' ' 5 16 Keyword_print 5 40 Op_subtract 6 16 Keyword_putc 6 40 Op_less 7 16 Keyword_if 7 40 Op_greater 8 16 Keyword_else 8 40 Op_lessequal 9 16 Keyword_while 9 40 Op_greaterequal 10 16 LeftBrace 10 40 Op_equal 11 16 RightBrace 11 40 Op_notequal 12 16 LeftParen 12 40 Op_and 13 16 RightParen 13 40 Op_or 14 16 Op_subtract 14 40 Semicolon 15 16 Op_not 15 40 Comma 16 16 Op_multiply 16 40 Op_assign 17 16 Op_divide 17 40 Integer 42 18 16 Op_mod 18 40 String "String literal" 19 16 Op_add 19 40 Identifier variable_name 20 26 Integer 10 21 26 Integer 92 22 26 Integer 32 23 1 End_of_input Test Case 4: /*** test printing, embedded \n and comments with lots of '*' ***/ print(42); print("\nHello World\nGood Bye\nok\n"); print("Print a slash n - \\n.\n"); 2 1 Keyword_print 2 6 LeftParen 2 7 Integer 42 2 9 RightParen 2 10 Semicolon 3 1 Keyword_print 3 6 LeftParen 3 7 String "\nHello World\nGood Bye\nok\n" 3 38 RightParen 3 39 Semicolon 4 1 Keyword_print 4 6 LeftParen 4 7 String "Print a slash n - \\n.\n" 4 33 RightParen 4 34 Semicolon 5 1 End_of_input Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Syntax Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#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   {inpf, outf, exit_status} = case {inpf_name, outf_name, exit_status} do {"-", "-", 0} -> {:stdio, :stdio, 0} {name1, "-", 0} -> {inpf, exit_status} = open_file(name1, [:read]) {inpf, :stdio, exit_status} {"-", name2, 0} -> {outf, exit_status} = open_file(name2, [:write]) {:stdio, outf, exit_status} {name1, name2, 0} -> {inpf, exit_status} = open_file(name1, [:read]) if exit_status != 0 do {inpf, name2, exit_status} else {outf, exit_status} = open_file(name2, [:write]) {inpf, outf, exit_status} end _ -> {inpf_name, outf_name, exit_status} end   exit_status = case exit_status do 0 -> main_program inpf, outf _ -> exit_status end   # Choose one. System.halt exit_status # Fast exit. #System.stop exit_status # Laborious cleanup. end   def main_program inpf, outf do inp = make_inp inpf scan_text outf, inp exit_status = 0 exit_status end   def open_file name, rw do case File.open name, rw do {:ok, f} -> {f, 0} _ -> IO.write :stderr, "Cannot open " IO.write :stderr, name case rw do [:read] -> IO.puts " for input" [:write] -> IO.puts " for output" end {name, 1} end end   def scan_text outf, inp do {toktup, inp} = get_next_token inp print_token outf, toktup case toktup do {"End_of_input", _, _, _} -> :ok _ -> scan_text outf, inp end end   def print_token outf, {tok, arg, line_no, column_no} do IO.write outf, (String.pad_leading "#{line_no}", 5) IO.write outf, " " IO.write outf, (String.pad_leading "#{column_no}", 5) IO.write outf, " " IO.write outf, tok case tok do "Identifier" -> IO.write outf, " " IO.write outf, arg "Integer" -> IO.write outf, " " IO.write outf, arg "String" -> IO.write outf, " " IO.write outf, arg _ -> :ok end IO.puts outf, "" end   ###------------------------------------------------------------------- ### ### The token dispatcher. ###   def get_next_token inp do inp = skip_spaces_and_comments inp {ch, inp} = get_ch inp {chr, line_no, column_no} = ch ln = line_no cn = column_no case chr do  :eof -> {{"End_of_input", "", ln, cn}, inp} "," -> {{"Comma", ",", ln, cn}, inp} ";" -> {{"Semicolon", ";", ln, cn}, inp} "(" -> {{"LeftParen", "(", ln, cn}, inp} ")" -> {{"RightParen", ")", ln, cn}, inp} "{" -> {{"LeftBrace", "{", ln, cn}, inp} "}" -> {{"RightBrace", "}", ln, cn}, inp} "*" -> {{"Op_multiply", "*", ln, cn}, inp} "/" -> {{"Op_divide", "/", ln, cn}, inp} "%" -> {{"Op_mod", "%", ln, cn}, inp} "+" -> {{"Op_add", "+", ln, cn}, inp} "-" -> {{"Op_subtract", "-", ln, cn}, inp} "<" -> {ch1, inp} = get_ch inp {chr1, _, _} = ch1 case chr1 do "=" -> {{"Op_lessequal", "<=", ln, cn}, inp} _ -> {{"Op_less", "<", ln, cn}, (push_back ch1, inp)} end ">" -> {ch1, inp} = get_ch inp {chr1, _, _} = ch1 case chr1 do "=" -> {{"Op_greaterequal", ">=", ln, cn}, inp} _ -> {{"Op_greater", ">", ln, cn}, (push_back ch1, inp)} end "=" -> {ch1, inp} = get_ch inp {chr1, _, _} = ch1 case chr1 do "=" -> {{"Op_equal", "==", ln, cn}, inp} _ -> {{"Op_assign", "=", ln, cn}, (push_back ch1, inp)} end "!" -> {ch1, inp} = get_ch inp {chr1, _, _} = ch1 case chr1 do "=" -> {{"Op_notequal", "!=", ln, cn}, inp} _ -> {{"Op_not", "!", ln, cn}, (push_back ch1, inp)} end "&" -> {ch1, inp} = get_ch inp {chr1, _, _} = ch1 case chr1 do "&" -> {{"Op_and", "&&", ln, cn}, inp} _ -> unexpected_character ln, cn, chr end "|" -> {ch1, inp} = get_ch inp {chr1, _, _} = ch1 case chr1 do "|" -> {{"Op_or", "||", ln, cn}, inp} _ -> unexpected_character ln, cn, chr end "\"" -> inp = push_back ch, inp scan_string_literal inp "'" -> inp = push_back ch, inp scan_character_literal inp _ -> cond do String.match? chr, ~r/^[[:digit:]]$/u -> inp = push_back ch, inp scan_integer_literal inp String.match? chr, ~r/^[[:alpha:]_]$/u -> inp = push_back ch, inp scan_identifier_or_reserved_word inp true -> unexpected_character ln, cn, chr end end end   ###------------------------------------------------------------------- ### ### Skipping past spaces and /* ... */ comments. ### ### Comments are treated exactly like a bit of whitespace. They never ### make it to the dispatcher. ###   def skip_spaces_and_comments inp do {ch, inp} = get_ch inp {chr, line_no, column_no} = ch cond do chr == :eof -> push_back ch, inp String.match? chr, ~r/^[[:space:]]$/u -> skip_spaces_and_comments inp chr == "/" -> {ch1, inp} = get_ch inp case ch1 do {"*", _, _} -> inp = scan_comment inp, line_no, column_no skip_spaces_and_comments inp _ -> push_back ch, (push_back ch1, inp) end true -> push_back ch, inp end end   def scan_comment inp, line_no, column_no do {ch, inp} = get_ch inp case ch do {:eof, _, _} -> unterminated_comment line_no, column_no {"*", _, _} -> {ch1, inp} = get_ch inp case ch1 do {:eof, _, _} -> unterminated_comment line_no, column_no {"/", _, _} -> inp _ -> scan_comment inp, line_no, column_no end _ -> scan_comment inp, line_no, column_no end end   ###------------------------------------------------------------------- ### ### Scanning of integer literals, identifiers, and reserved words. ### ### These three types of token are very similar to each other. ###   def scan_integer_literal inp do # Scan an entire word, not just digits. This way we detect # erroneous text such as "23skidoo". {line_no, column_no, inp} = get_position inp {word, inp} = scan_word inp if String.match? word, (~r/^[[:digit:]]+$/u) do {{"Integer", word, line_no, column_no}, inp} else invalid_integer_literal line_no, column_no, word end end   def scan_identifier_or_reserved_word inp do # It is assumed that the first character is of the correct type, # thanks to the dispatcher. {line_no, column_no, inp} = get_position inp {word, inp} = scan_word inp tok = case word do "if" -> "Keyword_if" "else" -> "Keyword_else" "while" -> "Keyword_while" "print" -> "Keyword_print" "putc" -> "Keyword_putc" _ -> "Identifier" end {{tok, word, line_no, column_no}, inp} end   def scan_word inp, word\\"" do {ch, inp} = get_ch inp {chr, _, _} = ch if String.match? chr, (~r/^[[:alnum:]_]$/u) do scan_word inp, (word <> chr) else {word, (push_back ch, inp)} end end   def get_position inp do {ch, inp} = get_ch inp {_, line_no, column_no} = ch inp = push_back ch, inp {line_no, column_no, inp} end   ###------------------------------------------------------------------- ### ### Scanning of string literals. ### ### It is assumed that the first character is the opening quote, and ### that the closing quote is the same character. ###   def scan_string_literal inp do {ch, inp} = get_ch inp {quote_mark, line_no, column_no} = ch {contents, inp} = scan_str_lit inp, ch {{"String", quote_mark <> contents <> quote_mark, line_no, column_no}, inp} end   def scan_str_lit inp, ch, contents\\"" do {quote_mark, line_no, column_no} = ch {ch1, inp} = get_ch inp {chr1, line_no1, column_no1} = ch1 if chr1 == quote_mark do {contents, inp} else case chr1 do  :eof -> eoi_in_string_literal line_no, column_no "\n" -> eoln_in_string_literal line_no, column_no "\\" -> {ch2, inp} = get_ch inp {chr2, _, _} = ch2 case chr2 do "n" -> scan_str_lit inp, ch, (contents <> "\\n") "\\" -> scan_str_lit inp, ch, (contents <> "\\\\") _ -> unsupported_escape line_no1, column_no1, chr2 end _ -> scan_str_lit inp, ch, (contents <> chr1) end end end   ###------------------------------------------------------------------- ### ### Scanning of character literals. ### ### It is assumed that the first character is the opening quote, and ### that the closing quote is the same character. ### ### The tedious part of scanning a character literal is distinguishing ### between the kinds of lexical error. (One might wish to modify the ### code to detect, as a distinct kind of error, end of line within a ### character literal.) ###   def scan_character_literal inp do {ch, inp} = get_ch inp {_, line_no, column_no} = ch {ch1, inp} = get_ch inp {chr1, line_no1, column_no1} = ch1 {intval, inp} = case chr1 do  :eof -> unterminated_character_literal line_no, column_no "\\" -> {ch2, inp} = get_ch inp {chr2, _, _} = ch2 case chr2 do  :eof -> unterminated_character_literal line_no, column_no "n" -> {(:binary.first "\n"), inp} "\\" -> {(:binary.first "\\"), inp} _ -> unsupported_escape line_no1, column_no1, chr2 end _ -> {(:binary.first chr1), inp} end inp = check_character_literal_end inp, ch {{"Integer", "#{intval}", line_no, column_no}, inp} end   def check_character_literal_end inp, ch do {chr, _, _} = ch {{chr1, _, _}, inp} = get_ch inp if chr1 == chr do inp else # Lexical error. find_char_lit_end inp, ch end end   def find_char_lit_end inp, ch do {chr, line_no, column_no} = ch {{chr1, _, _}, inp} = get_ch inp if chr1 == chr do multicharacter_literal line_no, column_no else case chr1 do  :eof -> unterminated_character_literal line_no, column_no _ -> find_char_lit_end inp, ch end end end   ###------------------------------------------------------------------- ### ### Character-at-a-time input, with unrestricted pushback, and with ### line and column numbering. ###   def make_inp inpf do {inpf, [], 1, 1} end   def get_ch {inpf, pushback, line_no, column_no} do case pushback do [head | tail] -> {head, {inpf, tail, line_no, column_no}} [] -> case IO.read(inpf, 1) do  :eof -> {{:eof, line_no, column_no}, {inpf, pushback, line_no, column_no}} {:error, _} -> {{:eof, line_no, column_no}, {inpf, pushback, line_no, column_no}} chr -> case chr do "\n" -> {{chr, line_no, column_no}, {inpf, pushback, line_no + 1, 1}} _ -> {{chr, line_no, column_no}, {inpf, pushback, line_no, column_no + 1}} end end end end   def push_back ch, {inpf, pushback, line_no, column_no} do {inpf, [ch | pushback], line_no, column_no} end   ###------------------------------------------------------------------- ### ### Lexical and usage errors. ###   def unterminated_comment line_no, column_no do raise "#{scriptname()}: unterminated comment at #{line_no}:#{column_no}" end   def invalid_integer_literal line_no, column_no, word do raise "#{scriptname()}: invalid integer literal #{word} at #{line_no}:#{column_no}" end   def unsupported_escape line_no, column_no, chr do raise "#{scriptname()}: unsupported escape \\#{chr} at #{line_no}:#{column_no}" end   def eoi_in_string_literal line_no, column_no do raise "#{scriptname()}: end of input in string literal starting at #{line_no}:#{column_no}" end   def eoln_in_string_literal line_no, column_no do raise "#{scriptname()}: end of line in string literal starting at #{line_no}:#{column_no}" end   def multicharacter_literal line_no, column_no do raise "#{scriptname()}: unsupported multicharacter literal at #{line_no}:#{column_no}" end   def unterminated_character_literal line_no, column_no do raise "#{scriptname()}: unterminated character literal starting at #{line_no}:#{column_no}" end   def unexpected_character line_no, column_no, chr do raise "#{scriptname()}: unexpected character '#{chr}' at #{line_no}:#{column_no}" end   def usage_error() do IO.puts "Usage: #{scriptname()} [INPUTFILE [OUTPUTFILE]]" IO.puts "If either of INPUTFILE or OUTPUTFILE is not present or is \"-\"," IO.puts "standard input or standard output is used, respectively." exit_status = 2 exit_status end   def scriptname() do Path.basename(__ENV__.file) end   #---------------------------------------------------------------------   end ## module Lex   Lex.main(System.argv)