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/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"
#Neko
Neko
/* command line arguments, neko */ var argc = $asize($loader.args)   /* Display count and arguments, indexed from 0, no script name included */ $print("There are ", argc, " arguments\n")   var arg = 0 while arg < argc $print($loader.args[arg ++= 1], "\n")
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.)
#Elena
Elena
//single line comment   /*multiple 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.)
#Elixir
Elixir
  # single line comment  
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.
#Julia
Julia
julia> Pkg.add("CellularAutomata") INFO: Installing CellularAutomata v0.1.2 INFO: Package database updated   julia> using CellularAutomata   julia> gameOfLife{T<:Int}(n::T, m::T, gen::T) = CA2d([3], [2,3], int(randbool(n, m)), gen) gameOfLife (generic function with 1 method)   julia> gameOfLife(15, 30, 5) 30x15x5 Cellular Automaton
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.
#Dragon
Dragon
if(a == b) { add() } else if(a == c) less() //{}'s optional for one-liners else { both() }
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
#Raku
Raku
[eq] @strings # All equal [lt] @strings # Strictly ascending
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
#Red
Red
Red []   list1: ["asdf" "Asdf" "asdf"] list2: ["asdf" "bsdf" "asdf"] list3: ["asdf" "asdf" "asdf"]   all-equal?: func [list][ 1 = length? unique/case list ] sorted?: func [list][ list == sort/case copy list ]  ;; sort without copy would modify list !   print all-equal? list1 print sorted? list1   print all-equal? list2 print sorted? list2   print all-equal? list3 print sorted? list3  
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.
#Lasso
Lasso
#!/usr/bin/lasso9   local(collection = array( array, array("ABC"), array("ABC", "DEF"), array("ABC", "DEF", "G", "H") ) )   with words in #collection do { if(#words -> size > 1) => { local(last = #words -> last) #words -> removelast stdoutnl('{' + #words -> join(', ') + ' and ' + #last'}') else(#words -> size == 1) stdoutnl('{' + #words -> first + '}') else stdoutnl('{}') }   }
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.
#Liberty_BASIC
Liberty BASIC
  do read in$ if in$ ="END" then wait w =wordCount( in$) select case w case 0 o$ ="{}" case 1 o$ ="{" +in$ +"}" case 2 o$ ="{" +word$( in$, 1) +" and " +word$( in$, 2) +"}" case else o$ ="{" o$ =o$ +word$( in$, 1) for k =2 to w -1 o$ =o$ +", " +word$( in$, k) next k o$ =o$ +" and " +word$( in$, w) +"}" end select if w =1 then print "'"; in$; "'"; " held "; w; " word. "; tab( 30); o$ else print "'"; in$; "'"; " held "; w; " words. "; tab( 30); o$ end if loop until 0   wait   function wordCount( IN$) wordCount =1 for i =1 to len( IN$) if mid$( IN$, i, 1) =" " then wordCount =wordCount +1 next i end function   end   data "" 'No input words. data "ABC" 'One input word. data "ABC DEF" 'Two words. data "ABC DEF G" 'Three words. data "ABC DEF G H" 'Four words.   data "END" 'Sentinel for EOD.  
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
#R
R
library(gtools) combinations(3, 2, c("iced", "jam", "plain"), set = FALSE, repeats.allowed = TRUE) nrow(combinations(10, 3, repeats.allowed = TRUE))
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
#Racket
Racket
  #lang racket (define (combinations xs k) (cond [(= k 0) '(())] [(empty? xs) '()] [(append (combinations (rest xs) k) (map (λ(x) (cons (first xs) x)) (combinations xs (- k 1))))]))  
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
#QB64
QB64
dim shared source as string, the_ch as string, tok as string, toktyp as string dim shared line_n as integer, col_n as integer, text_p as integer, err_line as integer, err_col as integer, errors as integer   declare function isalnum&(s as string) declare function isalpha&(s as string) declare function isdigit&(s as string) declare sub divide_or_comment declare sub error_exit(line_n as integer, col_n as integer, msg as string) declare sub follow(c as string, typ2 as string, typ1 as string) declare sub nextch declare sub nexttok declare sub read_char_lit declare sub read_ident declare sub read_number declare sub read_string   const c_integer = "Integer", c_ident = "Identifier", c_string = "String"   dim out_fn as string, out_tok as string   if command$(1) = "" then print "Expecting a filename": end open command$(1) for binary as #1 source = space$(lof(1)) get #1, 1, source close #1   out_fn = command$(2): if out_fn <> "" then open out_fn for output as #1   line_n = 1: col_n = 0: text_p = 1: the_ch = " "   do call nexttok select case toktyp case c_integer, c_ident, c_string: out_tok = tok case else: out_tok = "" end select if out_fn = "" then print err_line, err_col, toktyp, out_tok else print #1, err_line, err_col, toktyp, out_tok end if loop until errors or tok = "" if out_fn <> "" then close #1 end   ' get next tok, toktyp sub nexttok toktyp = "" restart: err_line = line_n: err_col = col_n: tok = the_ch select case the_ch case " ", chr$(9), chr$(10): call nextch: goto restart case "/": call divide_or_comment: if tok = "" then goto restart   case "%": call nextch: toktyp = "Op_mod" case "(": call nextch: toktyp = "LeftParen" case ")": call nextch: toktyp = "RightParen" case "*": call nextch: toktyp = "Op_multiply" case "+": call nextch: toktyp = "Op_add" case ",": call nextch: toktyp = "Comma" case "-": call nextch: toktyp = "Op_subtract" case ";": call nextch: toktyp = "Semicolon" case "{": call nextch: toktyp = "LeftBrace" case "}": call nextch: toktyp = "RightBrace"   case "&": call follow("&", "Op_and", "") case "|": call follow("|", "Op_or", "") case "!": call follow("=", "Op_notequal", "Op_not") case "<": call follow("=", "Op_lessequal", "Op_less") case "=": call follow("=", "Op_equal", "Op_assign") case ">": call follow("=", "Op_greaterequal", "Op_greater")   case chr$(34): call read_string case chr$(39): call read_char_lit   case "": toktyp = "End_of_input"   case else if isdigit&(the_ch) then call read_number elseif isalpha&(the_ch) then call read_ident else call nextch end if end select end sub   sub follow(c as string, if_both as string, if_one as string) call nextch if the_ch = c then tok = tok + the_ch call nextch toktyp = if_both else if if_one = "" then call error_exit(line_n, col_n, "Expecting " + c): exit sub toktyp = if_one end if end sub   sub read_string toktyp = c_string call nextch do tok = tok + the_ch select case the_ch case chr$(10): call error_exit(line_n, col_n, "EOL in string"): exit sub case "": call error_exit(line_n, col_n, "EOF in string"): exit sub case chr$(34): call nextch: exit sub case else: call nextch end select loop end sub   sub read_char_lit toktyp = c_integer call nextch if the_ch = chr$(39) then call error_exit(err_line, err_col, "Empty character constant"): exit sub end if   if the_ch = "\" then call nextch if the_ch = "n" then tok = "10" elseif the_ch = "\" then tok = "92" else call error_exit(line_n, col_n, "Unknown escape sequence:" + the_ch): exit sub end if else tok = ltrim$(str$(asc(the_ch))) end if   call nextch if the_ch <> chr$(39) then call error_exit(line_n, col_n, "Multi-character constant"): exit sub end if call nextch end sub   sub divide_or_comment call nextch if the_ch <> "*" then toktyp = "Op_divide" else ' skip comments tok = "" call nextch do if the_ch = "*" then call nextch if the_ch = "/" then call nextch exit sub end if elseif the_ch = "" then call error_exit(line_n, col_n, "EOF in comment"): exit sub else call nextch end if loop end if end sub   sub read_ident do call nextch if not isalnum&(the_ch) then exit do tok = tok + the_ch loop select case tok case "else": toktyp = "keyword_else" case "if": toktyp = "keyword_if" case "print": toktyp = "keyword_print" case "putc":: toktyp = "keyword_putc" case "while": toktyp = "keyword_while" case else: toktyp = c_ident end select end sub   sub read_number toktyp = c_integer do call nextch if not isdigit&(the_ch) then exit do tok = tok + the_ch loop   if isalpha&(the_ch) then call error_exit(err_line, err_col, "Bogus number: " + tok + the_ch): exit sub end if end sub   function isalpha&(s as string) dim c as string c = left$(s, 1) isalpha& = c <> "" and instr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_", c) > 0 end function   function isdigit&(s as string) dim c as string c = left$(s, 1) isdigit& = c <> "" and instr("0123456789", c) > 0 end function   function isalnum&(s as string) dim c as string c = left$(s, 1) isalnum& = c <> "" and instr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_", c) > 0 end function   ' get next char - fold cr/lf into just lf sub nextch the_ch = "" col_n = col_n + 1 if text_p > len(source) then exit sub   the_ch = mid$(source, text_p, 1) text_p = text_p + 1   if the_ch = chr$(13) then the_ch = chr$(10) if text_p <= len(source) then if mid$(source, text_p, 1) = chr$(10) then text_p = text_p + 1 end if end if end if   if the_ch = chr$(10) then line_n = line_n + 1 col_n = 0 end if   end sub   sub error_exit(line_n as integer, col_n as integer, msg as string) errors = -1 print line_n, col_n, msg end end sub  
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"
#Nemerle
Nemerle
using System; using System.Console;   module CLArgs { Main(args : array[string]) : void { foreach (arg in args) Write($"$arg "); // using the array passed to Main(), everything after the program name Write("\n");   def cl_args = Environment.GetCommandLineArgs(); // also gets program name foreach (cl_arg in cl_args) Write($"$cl_arg "); } }
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"
#NetRexx
NetRexx
/* NetRexx */ -- sample arguments: -c "alpha beta" -h "gamma" say "program arguments:" arg  
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"
#Nim
Nim
import os echo "program name: ", getAppFilename() echo "Arguments:" for arg in commandLineParams(): echo arg
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.)
#Elm
Elm
  -- a single line comment   {- a multiline comment {- can be nested -} -}  
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.)
#Emacs_Lisp
Emacs Lisp
; This is a comment
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.
#Kotlin
Kotlin
// version 1.2.0   import java.util.Random   val rand = Random(0) // using a seed to produce same output on each run   enum class Pattern { BLINKER, GLIDER, RANDOM }   class Field(val w: Int, val h: Int) { val s = List(h) { BooleanArray(w) }   operator fun set(x: Int, y: Int, b: Boolean) { s[y][x] = b }   fun next(x: Int, y: Int): Boolean { var on = 0 for (i in -1..1) { for (j in -1..1) { if (state(x + i, y + j) && !(j == 0 && i == 0)) on++ } } return on == 3 || (on == 2 && state(x, y)) }   fun state(x: Int, y: Int): Boolean { if ((x !in 0 until w) || (y !in 0 until h)) return false return s[y][x] } }   class Life(val pattern: Pattern) { val w: Int val h: Int var a: Field var b: Field   init { when (pattern) { Pattern.BLINKER -> { w = 3 h = 3 a = Field(w, h) b = Field(w, h) a[0, 1] = true a[1, 1] = true a[2, 1] = true }   Pattern.GLIDER -> { w = 4 h = 4 a = Field(w, h) b = Field(w, h) a[1, 0] = true a[2, 1] = true for (i in 0..2) a[i, 2] = true }   Pattern.RANDOM -> { w = 80 h = 15 a = Field(w, h) b = Field(w, h) for (i in 0 until w * h / 2) { a[rand.nextInt(w), rand.nextInt(h)] = true } } } }   fun step() { for (y in 0 until h) { for (x in 0 until w) { b[x, y] = a.next(x, y) } } val t = a a = b b = t }   override fun toString(): String { val sb = StringBuilder() for (y in 0 until h) { for (x in 0 until w) { val c = if (a.state(x, y)) '#' else '.' sb.append(c) } sb.append('\n') } return sb.toString() } }   fun main(args: Array<String>) { val lives = listOf( Triple(Life(Pattern.BLINKER), 3, "BLINKER"), Triple(Life(Pattern.GLIDER), 4, "GLIDER"), Triple(Life(Pattern.RANDOM), 100, "RANDOM") ) for ((game, gens, title) in lives) { println("$title:\n") repeat(gens + 1) { println("Generation: $it\n$game") Thread.sleep(30) game.step() } println() } }
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.
#DWScript
DWScript
if a: pass elseif b: pass else: # c, maybe? pass
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
#REXX
REXX
/* REXX --------------------------------------------------------------- * 28.06.2014 Walter Pachl *--------------------------------------------------------------------*/ Call mklist 'ABC','AA','BB','CC' Call test 'ABC' Call mklist 'AAA','AA','AA','AA' Call mklist 'ACB','AA','CC','BB' Call test 'AAA' Call test 'ACB' Exit   mklist: list=arg(1) do i=1 by 1 To arg()-1 call value list'.'i,arg(i+1) End Call value list'.0',i-1 Return   test: Parse Arg list all_equal=1 increasing=1 Do i=1 To value(list'.0')-1 While all_equal | increasing i1=i+1 Select When value(list'.i1')==value(list'.i') Then increasing=0 When value(list'.i1')<<value(list'.i') Then Do all_equal=0 increasing=0 End When value(list'.i1')>>value(list'.i') Then all_equal=0 End End Select When all_equal Then Say 'List' value(list)': all elements are equal' When increasing Then Say 'List' value(list)': elements are in increasing order' Otherwise Say 'List' value(list)': neither equal nor in increasing order' End Return
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.
#Logo
Logo
to join :delimiter :list [:result []] output cond [ [ [empty? :list]  :result ] [ [empty? :result] (join :delimiter butfirst :list first :list) ] [ else (join :delimiter butfirst :list (word :result :delimiter first :list)) ] ] end   to quibble :list local "length make "length count :list make "text ( ifelse [:length <= 2] [ (join "\ and\  :list) ] [ (join "\ and\ (sentence join ",\ butlast :list last :list)) ]) output ifelse [empty? :text] "\{\} [(word "\{ :text "\})] end   foreach [ [] [ABC] [ABC DEF] [ABC DEF G H] ] [ print quibble ? ]   bye
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.
#Lua
Lua
function quibble (strTab) local outString, join = "{" for strNum = 1, #strTab do if strNum == #strTab then join = "" elseif strNum == #strTab - 1 then join = " and " else join = ", " end outString = outString .. strTab[strNum] .. join end return outString .. '}' end   local testCases = { {}, {"ABC"}, {"ABC", "DEF"}, {"ABC", "DEF", "G", "H"} } for _, input in pairs(testCases) do print(quibble(input)) end
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
#Raku
Raku
my @S = <iced jam plain>; my $k = 2;   .put for [X](@S xx $k).unique(as => *.sort.cache, with => &[eqv])
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
#REXX
REXX
/*REXX pgm displays combination sets with repetitions for X things taken Y at a time*/ call RcombN 3, 2, 'iced jam plain' /*The 1st part of Rosetta Code task. */ call RcombN -10, 3, 'Iced jam plain' /* " 2nd " " " " " */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ RcombN: procedure; parse arg x,y,syms; tell= x>0; x=abs(x); z=x+1 /*X>0? Show combo*/ say copies('─',15) x "doughnut selection taken" y 'at a time:' /*display title. */ do i=1 for words(syms); $.i=word(syms, i) /*assign symbols.*/ end /*i*/ @.=1 /*assign default.*/ do #=1; if tell then call show /*display combos?*/ @[email protected] + 1; if @.y==z then if .(y-1) then leave /* ◄─── recursive*/ end /*#*/ say copies('═',15) # "combinations."; say; say /*display answer.*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ .: procedure expose @. y z; parse arg ?; if ?==0 then return 1; p=@.? +1 if p==z then return .(? -1); do j=? to y; @.j=p; end /*j*/; return 0 /*──────────────────────────────────────────────────────────────────────────────────────*/ show: L=; do c=1 for y; [email protected]; L=L $._; end /*c*/; say L; return
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
#Racket
Racket
  #lang racket (require parser-tools/lex)   (define-lex-abbrevs [letter (union (char-range #\a #\z) (char-range #\A #\Z))] [digit (char-range #\0 #\9)] [underscore #\_] [identifier (concatenation (union letter underscore) (repetition 0 +inf.0 (union letter digit underscore)))] [integer (repetition 1 +inf.0 digit)] [char-content (char-complement (char-set "'\n"))] [char-literal (union (concatenation #\' char-content #\') "'\\n'" "'\\\\'")] [string-content (union (char-complement (char-set "\"\n")))] [string-literal (union (concatenation #\" (repetition 0 +inf.0 string-content) #\") "\"\\n\"" "\"\\\\\"")] [keyword (union "if" "else" "while" "print" "putc")] [operator (union "*" "/" "%" "+" "-" "-" "<" "<=" ">" ">=" "==" "!=" "!" "=" "&&" "||")] [symbol (union "(" ")" "{" "}" ";" ",")] [comment (concatenation "/*" (complement (concatenation any-string "*/" any-string)) "*/")])   (define operators-ht (hash "*" 'Op_multiply "/" 'Op_divide "%" 'Op_mod "+" 'Op_add "-" 'Op_subtract "<" 'Op_less "<=" 'Op_lessequal ">" 'Op_greater ">=" 'Op_greaterequal "==" 'Op_equal "!=" 'Op_notequal "!" 'Op_not "=" 'Op_assign "&&" 'Op_and "||" 'Op_or))   (define symbols-ht (hash "(" 'LeftParen ")" 'RightParen "{" 'LeftBrace "}" 'RightBrace ";" 'Semicolon "," 'Comma))   (define (lexeme->keyword l) (string->symbol (~a "Keyword_" l))) (define (lexeme->operator l) (hash-ref operators-ht l)) (define (lexeme->symbol l) (hash-ref symbols-ht l)) (define (lexeme->char l) (match l ["'\\\\'" #\\] ["'\\n'" #\newline] [_ (string-ref l 1)]))   (define (token name [value #f]) (cons name (if value (list value) '())))   (define (lex ip) (port-count-lines! ip) (define my-lexer (lexer-src-pos [integer (token 'Integer (string->number lexeme))] [char-literal (token 'Integer (char->integer (lexeme->char lexeme)))] [string-literal (token 'String lexeme)] [keyword (token (lexeme->keyword lexeme))] [operator (token (lexeme->operator lexeme))] [symbol (token (lexeme->symbol lexeme))] [comment #f] [whitespace #f] [identifier (token 'Identifier lexeme)] [(eof) (token 'End_of_input)])) (define (next-token) (my-lexer ip)) next-token)   (define (string->tokens s) (port->tokens (open-input-string s)))   (define (port->tokens ip) (define next-token (lex ip)) (let loop () (match (next-token) [(position-token t (position offset line col) _) (set! col (+ col 1)) ; output is 1-based (match t [#f (loop)] ; skip whitespace/comments [(list 'End_of_input) (list (list line col 'End_of_input))] [(list name value) (cons (list line col name value) (loop))] [(list name) (cons (list line col name) (loop))] [_ (error)])])))   (define test1 #<<TEST /* Hello world */ print("Hello, World!\n");   TEST )   (define test2 #<<TEST /* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, "\n");   TEST )   (define test3 #<<TEST /* 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 */ ' ' TEST )   (define test4 #<<TEST /*** 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"); TEST )   (define test5 #<<TEST count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } TEST )   (define (display-tokens ts) (for ([t ts]) (for ([x t]) (display x) (display "\t\t")) (newline)))   "TEST 1" (display-tokens (string->tokens test1)) "TEST 2" (display-tokens (string->tokens test2)) "TEST 3" (display-tokens (string->tokens test3)) "TEST 4" (display-tokens (string->tokens test4)) "TEST 5" (display-tokens (string->tokens test5))  
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"
#Oberon-2
Oberon-2
  MODULE CommandLineArguments; IMPORT NPCT:Args, Out := NPCT:Console;   BEGIN Out.String("Args number: ");Out.Int(Args.Number(),0);Out.Ln; Out.String("0.- : ");Out.String(Args.AsString(0));Out.Ln; Out.String("1.- : ");Out.String(Args.AsString(1));Out.Ln; Out.String("2.- : ");Out.String(Args.AsString(2));Out.Ln; Out.String("3.- : ");Out.String(Args.AsString(3));Out.Ln; Out.String("4.-: ");Out.String(Args.AsString(4));Out.Ln END CommandLineArguments.  
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"
#Objeck
Objeck
  class Line { function : Main(args : String[]) ~ Nil { each(i : args) { args[i]->PrintLine(); }; } }  
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.)
#Erlang
Erlang
% Erlang comments begin with "%" and extend to the end of the line.
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.)
#ERRE
ERRE
  ! Standard ERRE comments begin with ! and extend to the end of the line   PRINT("this is code") ! comment after statement  
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.
#Lua
Lua
local function T2D(w,h) local t={} for y=1,h do t[y]={} for x=1,w do t[y][x]=0 end end return t end   local Life = { new = function(self,w,h) return setmetatable({ w=w, h=h, gen=1, curr=T2D(w,h), next=T2D(w,h)}, {__index=self}) end, set = function(self, coords) for i = 1, #coords, 2 do self.curr[coords[i+1]][coords[i]] = 1 end end, evolve = function(self) local curr, next = self.curr, self.next local ym1, y, yp1 = self.h-1, self.h, 1 for i = 1, self.h do local xm1, x, xp1 = self.w-1, self.w, 1 for j = 1, self.w do local sum = curr[ym1][xm1] + curr[ym1][x] + curr[ym1][xp1] + curr[y][xm1] + curr[y][xp1] + curr[yp1][xm1] + curr[yp1][x] + curr[yp1][xp1] next[y][x] = ((sum==2) and curr[y][x]) or ((sum==3) and 1) or 0 xm1, x, xp1 = x, xp1, xp1+1 end ym1, y, yp1 = y, yp1, yp1+1 end self.curr, self.next, self.gen = self.next, self.curr, self.gen+1 end, render = function(self) print("Generation "..self.gen..":") for y = 1, self.h do for x = 1, self.w do io.write(self.curr[y][x]==0 and "□ " or "■ ") end print() end end }
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.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
if a: pass elseif b: pass else: # c, maybe? pass
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
#Ruby
Ruby
strings.uniq.one? # all equal? strings == strings.uniq.sort # ascending?
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
#Rust
Rust
fn strings_are_equal(seq: &[&str]) -> bool { match seq { &[] | &[_] => true, &[x, y, ref tail @ ..] if x == y => strings_are_equal(&[&[y], tail].concat()), _ => false } }   fn asc_strings(seq: &[&str]) -> bool { match seq { &[] | &[_] => true, &[x, y, ref tail @ ..] if x < y => asc_strings(&[&[y], tail].concat()), _ => false } }
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.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { function f$ { what$=mid$(trim$(letter$),2) what$=Left$(what$, len(what$)-1) flush ' erase any argument from stack Data param$(what$) m=stack.size document resp$="{" if m>2 then { shift m-1, 2 ' get last two as first two push letter$+" and "+letter$ m-- ' one less shiftback m ' move to last position } while not empty { resp$=letter$+if$(not empty->", ", "") } =resp$+"}"   } \\ we use ? for Print  ? f$({[]})  ? f$({["ABC"]})  ? f$({["ABC", "DEF"]})  ? f$({["ABC","DEF", "G", "H"]}) } Checkit  
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.
#Maple
Maple
Quibble := proc( los ) uses StringTools; Fence( proc() if los = [] then "" elif numelems( los ) = 1 then los[ 1 ] else cat( Join( los[ 1 .. -2 ], ", " ), " and ", los[ -1 ] ) end if end(), "{", "}" ) end proc:
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S {\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
#Ring
Ring
  # Project : Combinations with repetitions   n = 2 k = 3 temp = [] comb = [] num = com(n, k) combinations(n, k) comb = sortfirst(comb, 1) see showarray(comb) + nl   func combinations(n, k) while true temp = [] for nr = 1 to k tm = random(n-1) + 1 add(temp, tm) next add(comb, temp) for p = 1 to len(comb) - 1 for q = p + 1 to len(comb) if (comb[p][1] = comb[q][1]) and (comb[p][2] = comb[q][2]) and (comb[p][3] = comb[q][3]) del(comb, p) ok next next if len(comb) = num exit ok end   func com(n, k) res = pow(n, k) return res   func showarray(vect) svect = "" for nrs = 1 to len(vect) svect = "[" + vect[nrs][1] + " " + vect[nrs][2] + " " + vect[nrs][3] + "]" + nl see svect next   Func sortfirst(alist, ind) aList = sort(aList,ind) for n = 1 to len(alist)-1 for m= n + 1 to len(aList) if alist[n][1] = alist[m][1] and alist[m][2] < alist[n][2] temp = alist[n] alist[n] = alist[m] alist[m] = temp ok next next for n = 1 to len(alist)-1 for m= n + 1 to len(aList) if alist[n][1] = alist[m][1] and alist[n][2] = alist[m][2] and alist[m][3] < alist[n][3] temp = alist[n] alist[n] = alist[m] alist[m] = temp ok next next return aList  
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
#Ruby
Ruby
possible_doughnuts = ['iced', 'jam', 'plain'].repeated_combination(2) puts "There are #{possible_doughnuts.count} possible doughnuts:" possible_doughnuts.each{|doughnut_combi| puts doughnut_combi.join(' and ')}   # Extra credit possible_doughnuts = [*1..1000].repeated_combination(30) # size returns the size of the enumerator, or nil if it can’t be calculated lazily. puts "", "#{possible_doughnuts.size} ways to order 30 donuts given 1000 types."  
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
#Raku
Raku
grammar tiny_C { rule TOP { ^ <.whitespace>? <tokens> + % <.whitespace> <.whitespace> <eoi> }   rule whitespace { [ <comment> + % <ws> | <ws> ] }   token comment { '/*' ~ '*/' .*? }   token tokens { [ | <operator> { make $/<operator>.ast } | <keyword> { make $/<keyword>.ast } | <symbol> { make $/<symbol>.ast } | <identifier> { make $/<identifier>.ast } | <integer> { make $/<integer>.ast } | <char> { make $/<char>.ast } | <string> { make $/<string>.ast } | <error> ] }   proto token operator {*} token operator:sym<*> { '*' { make 'Op_multiply' } } token operator:sym</> { '/'<!before '*'> { make 'Op_divide' } } token operator:sym<%> { '%' { make 'Op_mod' } } token operator:sym<+> { '+' { make 'Op_add' } } token operator:sym<-> { '-' { make 'Op_subtract' } } token operator:sym('<='){ '<=' { make 'Op_lessequal' } } token operator:sym('<') { '<' { make 'Op_less' } } token operator:sym('>='){ '>=' { make 'Op_greaterequal'} } token operator:sym('>') { '>' { make 'Op_greater' } } token operator:sym<==> { '==' { make 'Op_equal' } } token operator:sym<!=> { '!=' { make 'Op_notequal' } } token operator:sym<!> { '!' { make 'Op_not' } } token operator:sym<=> { '=' { make 'Op_assign' } } token operator:sym<&&> { '&&' { make 'Op_and' } } token operator:sym<||> { '||' { make 'Op_or' } }   proto token keyword {*} token keyword:sym<if> { 'if' { make 'Keyword_if' } } token keyword:sym<else> { 'else' { make 'Keyword_else' } } token keyword:sym<putc> { 'putc' { make 'Keyword_putc' } } token keyword:sym<while> { 'while' { make 'Keyword_while' } } token keyword:sym<print> { 'print' { make 'Keyword_print' } }   proto token symbol {*} token symbol:sym<(> { '(' { make 'LeftParen' } } token symbol:sym<)> { ')' { make 'RightParen' } } token symbol:sym<{> { '{' { make 'LeftBrace' } } token symbol:sym<}> { '}' { make 'RightBrace' } } token symbol:sym<;> { ';' { make 'Semicolon' } } token symbol:sym<,> { ',' { make 'Comma' } }   token identifier { <[_A..Za..z]><[_A..Za..z0..9]>* { make 'Identifier ' ~ $/ } } token integer { <[0..9]>+ { make 'Integer ' ~ $/ } }   token char { '\'' [<-[']> | '\n' | '\\\\'] '\'' { make 'Char_Literal ' ~ $/.subst("\\n", "\n").substr(1, *-1).ord } }   token string { '"' <-["\n]>* '"' #' { make 'String ' ~ $/; note 'Error: Unknown escape sequence.' and exit if (~$/ ~~ m:r/ <!after <[\\]>>[\\<-[n\\]>]<!before <[\\]>> /); } }   token eoi { $ { make 'End_of_input' } }   token error { | '\'''\'' { note 'Error: Empty character constant.' and exit } | '\'' <-[']> ** {2..*} '\'' { note 'Error: Multi-character constant.' and exit } | '/*' <-[*]>* $ { note 'Error: End-of-file in comment.' and exit } | '"' <-["]>* $ { note 'Error: End-of-file in string.' and exit } | '"' <-["]>*? \n { note 'Error: End of line in string.' and exit } #' } }   sub parse_it ( $c_code ) { my $l; my @pos = gather for $c_code.lines>>.chars.kv -> $line, $v { take [ $line + 1, $_ ] for 1 .. ($v+1); # v+1 for newline $l = $line+2; } @pos.push: [ $l, 1 ]; # capture eoi   for flat $c_code<tokens>.list, $c_code<eoi> -> $m { say join "\t", @pos[$m.from].fmt('%3d'), $m.ast; } }   my $tokenizer = tiny_C.parse(@*ARGS[0].IO.slurp); parse_it( $tokenizer );
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"
#Objective-C
Objective-C
NSArray *args = [[NSProcessInfo processInfo] arguments]; NSLog(@"This program is named %@.", [args objectAtIndex:0]); NSLog(@"There are %d arguments.", [args count] - 1); for (i = 1; i < [args count]; ++i){ NSLog(@"the argument #%d is %@", i, [args objectAtIndex: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"
#OCaml
OCaml
let () = Printf.printf "This program is named %s.\n" Sys.argv.(0); for i = 1 to Array.length Sys.argv - 1 do Printf.printf "the argument #%d is %s\n" i Sys.argv.(i) done
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.)
#Euphoria
Euphoria
-- This is a comment
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.
#ksh
ksh
  #!/bin/ksh # # Version AJM 93u+ 2012-08-01   # Conway's Game of Life   # # Variables: # integer RAND_MAX=32767 LIFE="�[07m �[m" NULL=" " typeset -a char=( "$NULL" "$LIFE" )   # # Input x y or default to 30x30, positive integers only # integer h=${1:-30} ; h=$(( h<=0 ? 30 : h )) # Height (y) integer w=${2:-30} ; w=$(( w<=0 ? 30 : w )) # Width (x)   # # Functions: #   # # Function _display(map, h, w) # function _display { typeset _dmap ; nameref _dmap="$1" typeset _h _w ; integer _h=$2 _w=$3   typeset _x _y ; integer _x _y   printf %s "�[H" for (( _y=0; _y<_h; _y++ )); do for (( _x=0; _x<_w; _x++ )); do printf %s "${char[_dmap[_y][_x]]}" done printf "%s\n" done }   # # Function _evolve(h, w) # _evolve() { typeset _h _w ; integer _h=$1 _w=$2   typeset _x _y _n _y1 _x1 ; integer _x _y _n _y1 _x1 typeset _new _newdef ; typeset -a _new   for (( _y=0; _y<_h; _y++ )); do for (( _x=0; _x<_w; _x++ )); do _n=0 for (( _y1=_y-1; _y1<=_y+1; _y1++ )); do for (( _x1=_x-1; _x1<=_x+1; _x1++ )); do (( _map[$(( (_y1 + _h) % _h ))][$(( (_x1 + _w) % _w ))] )) && (( _n++ )) done done (( _map[_y][_x] )) && (( _n-- )) _new[_y][_x]=$(( (_n==3) || (_n==2 && _map[_y][_x]) )) done done   for (( _y=0; _y<_h; _y++ )); do for (( _x=0; _x<_w; _x++ )); do _map[_y][_x]=${_new[_y][_x]} done done }   # # Function _game(h, w) # function _game { typeset _h ; integer _h=$1 typeset _w ; integer _w=$2   typeset _x _y ; integer _x _y typeset -a _map   for (( _y=0 ; _y<_h ; _y++ )); do for (( _x=0 ; _x<_h ; _x++ )); do _map[_x][_y]=$(( RANDOM < RAND_MAX / 10 ? 1 : 0 )) # seed map done done   while : ; do _display _map ${_h} ${_w} _evolve ${_h} ${_w} sleep 0.2 done }   ###### # main # ######   _game ${h} ${w}    
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.
#E
E
if (okay) { println("okay") } else if (!okay) { println("not okay") } else { println("not my day") }
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
#S-lang
S-lang
define equal_sl(sarr) { variable n = length(sarr), a0, i; if (n < 2) return 1;   a0 = sarr[0]; _for i (1, length(sarr)-1, 1) if (sarr[i] != a0) return 0;   return 1; } define ascending_sl(sarr) { variable n = length(sarr), a0, i; if (n < 2) return 1;   _for i (0, length(sarr)-2, 1) if (sarr[i] >= sarr[i+1]) return 0;   return 1; }     define equal_ai(sarr) { if (length(sarr) < 2) return 1; variable s0 = sarr[0]; return all(sarr[[1:]] == s0); }   define ascending_ai(sarr) { variable la = length(sarr); if (la < 2) return 1; return all(sarr[[0:la-2]] < sarr[[1:la-1]]); }   define atest(a) { () = printf("\n"); print(a);   () = printf("equal_sl=%d, ascending_sl=%d\n", equal_sl(a), ascending_sl(a)); () = printf("equal_ai=%d, ascending_ai=%d\n", equal_ai(a), ascending_ai(a)); }   atest(["AA","BB","CC"]); atest(["AA","AA","AA"]); atest(["AA","CC","BB"]); atest(["AA","ACB","BB","CC"]); atest(["single_element"]); atest(NULL);  
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
#Scala
Scala
  def strings_are_equal(seq:List[String]):Boolean = seq match { case Nil => true case s::Nil => true case el1 :: el2 :: tail => el1==el2 && strings_are_equal(el2::tail) }   def asc_strings(seq:List[String]):Boolean = seq match { case Nil => true case s::Nil => true case el1 :: el2 :: tail => el1.compareTo(el2) < 0 }    
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
quibble[words___] := ToString@{StringJoin@@ Replace[Riffle[{words}, ", "], {most__, ", ", last_} -> {most, " and ", last}]}
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.
#MATLAB_.2F_Octave
MATLAB / Octave
  function r = comma_quibbling(varargin) if isempty(varargin) r = ''; elseif length(varargin)==1; r = varargin{1}; else r = [varargin{end-1},' and ', varargin{end}]; for k=length(varargin)-2:-1:1, r = [varargin{k}, ', ', r]; end end end;  
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
#Rust
Rust
  // Iterator for the combinations of `arr` with `k` elements with repetitions. // Yields the combinations in lexicographical order. struct CombinationsWithRepetitions<'a, T: 'a> { // source array to get combinations from arr: &'a [T], // length of the combinations k: u32, // current counts of each object that represent the next combination counts: Vec<u32>, // whether there are any combinations left remaining: bool, }   impl<'a, T> CombinationsWithRepetitions<'a, T> { fn new(arr: &[T], k: u32) -> CombinationsWithRepetitions<T> { let mut counts = vec![0; arr.len()]; counts[arr.len() - 1] = k; CombinationsWithRepetitions { arr, k, counts, remaining: true, } } }   impl<'a, T> Iterator for CombinationsWithRepetitions<'a, T> { type Item = Vec<&'a T>;   fn next(&mut self) -> Option<Vec<&'a T>> { if !self.remaining { return None; } let mut comb = Vec::new(); for (count, item) in self.counts.iter().zip(self.arr.iter()) { for _ in 0..*count { comb.push(item); } } // this is lexicographically largest, and thus the last combination if self.counts[0] == self.k { self.remaining = false; } else { let n = self.counts.len(); for i in (1..n).rev() { if self.counts[i] > 0 { let original_value = self.counts[i]; self.counts[i - 1] += 1; for j in i..(n - 1) { self.counts[j] = 0; } self.counts[n - 1] = original_value - 1; break; } } } Some(comb) } }   fn main() { let collection = vec!["iced", "jam", "plain"]; for comb in CombinationsWithRepetitions::new(&collection, 2) { for item in &comb { print!("{} ", item) } println!() } }    
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
#Scala
Scala
  object CombinationsWithRepetition {   def multi[A](as: List[A], k: Int): List[List[A]] = (List.fill(k)(as)).flatten.combinations(k).toList   def main(args: Array[String]): Unit = { val doughnuts = multi(List("iced", "jam", "plain"), 2) for (combo <- doughnuts) println(combo.mkString(","))   val bonus = multi(List(0,1,2,3,4,5,6,7,8,9), 3).size println("There are "+bonus+" ways to choose 3 items from 10 choices") } }  
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
#RATFOR
RATFOR
###################################################################### # # The Rosetta Code scanner in Ratfor 77. # # # How to deal with FORTRAN 77 input is a problem. I use formatted # input, treating each line as an array of type CHARACTER--regrettably # of no more than some predetermined, finite length. It is a very # simple method and presents no significant difficulties, aside from # the restriction on line length of the input. # # # On a POSIX platform, the program can be compiled with f2c and run # somewhat as follows: # # ratfor77 lex-in-ratfor.r > lex-in-ratfor.f # f2c -C -Nc40 lex-in-ratfor.f # cc -O lex-in-ratfor.c -lf2c # ./a.out < compiler-tests/primes.t # # With gfortran, a little differently: # # ratfor77 lex-in-ratfor.r > lex-in-ratfor.f # gfortran -O2 -fcheck=all -std=legacy lex-in-ratfor.f # ./a.out < compiler-tests/primes.t # # # I/O is strictly from default input and to default output, which, on # POSIX systems, usually correspond respectively to standard input and # standard output. (I did not wish to have to deal with unit numbers; # these are now standardized in ISO_FORTRAN_ENV, but that is not # available in FORTRAN 77.) # #---------------------------------------------------------------------   # Some parameters you may with to modify.   define(LINESZ, 256) # Size of an input line. define(OUTLSZ, 512) # Size of an output line. define(PSHBSZ, 10) # Size of the character pushback buffer. define(STRNSZ, 4096) # Size of the string pool.   #---------------------------------------------------------------------   define(EOF, -1) define(NEWLIN, 10) # Unix newline (the LF control character). define(BACKSL, 92) # ASCII backslash.   define(ILINNO, 1) # Line number's index. define(ICOLNO, 2) # Column number's index.   define(CHRSZ, 3) # See ILINNO and ICOLNO above. define(ICHRCD, 3) # Character code's index.   define(TOKSZ, 5) # See ILINNO and ICOLNO above. define(ITOKNO, 3) # Token number's index. define(IARGIX, 4) # Index of the string pool index. define(IARGLN, 5) # Index of the string length.   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(LOC10, 1) # Location of "10" in the string pool. define(LOC92, 3) # Location of "92" in the string pool.   #---------------------------------------------------------------------   subroutine addstr (strngs, istrng, src, i0, n0, i, n)   # Add a string to the string pool.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character src(*) # Source string. integer i0, n0 # Index and length in source string. integer i, n # Index and length in string pool.   integer j   if (STRNSZ < istrng + (n0 - 1)) { write (*, '(''string pool exhausted'')') stop } for (j = 0; j < n0; j = j + 1) strngs(istrng + j) = src(i0 + j) i = istrng n = n0 istrng = istrng + n0 end   subroutine cpystr (strngs, i, n, dst, i0)   # Copy a string from the string pool to an output string.   implicit none   character strngs(STRNSZ) # String pool. integer i, n # Index and length in string pool. character dst(OUTLSZ) # Destination string. integer i0 # Index within destination string.   integer j   if (i0 < 1 || OUTLSZ < i0 + (n - 1)) { write (*, '(''string boundary exceeded'')') stop } for (j = 0; j < n; j = j + 1) dst(i0 + j) = strngs(i + j) end   #---------------------------------------------------------------------   subroutine getchr (line, linno, colno, pushbk, npshbk, chr)   # Get a character, with its line number and column number.   implicit none   character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back. integer chr(CHRSZ)   # End of file is indicated (as in C) by a negative "char code" # called "EOF".   character*20 fmt integer stat integer chr1(CHRSZ)   if (0 < npshbk) { chr(ICHRCD) = pushbk(ICHRCD, npshbk) chr(ILINNO) = pushbk(ILINNO, npshbk) chr(ICOLNO) = pushbk(ICOLNO, npshbk) npshbk = npshbk - 1 } else if (colno <= LINESZ) { chr(ICHRCD) = ichar (line(colno)) chr(ILINNO) = linno chr(ICOLNO) = colno colno = colno + 1 } else { # Return a newline character. chr(ICHRCD) = NEWLIN chr(ILINNO) = linno chr(ICOLNO) = colno   # Fetch a new line. linno = linno + 1 colno = 1   # Read a line of text as an array of characters. write (fmt, '(''('', I10, ''A1)'')') LINESZ read (*, fmt, iostat = stat) line   if (stat != 0) { # If end of file has been reached, push an EOF. chr1(ICHRCD) = EOF chr1(ILINNO) = linno chr1(ICOLNO) = colno call pshchr (pushbk, npshbk, chr1) } } end   subroutine pshchr (pushbk, npshbk, chr)   # Push back a character.   implicit none   integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back. integer chr(CHRSZ)   if (PSHBSZ <= npshbk) { write (*, '(''pushback buffer overfull'')') stop } npshbk = npshbk + 1 pushbk(ICHRCD, npshbk) = chr(ICHRCD) pushbk(ILINNO, npshbk) = chr(ILINNO) pushbk(ICOLNO, npshbk) = chr(ICOLNO) end   subroutine getpos (line, linno, colno, pushbk, npshbk, ln, cn)   # Get the position of the next character.   implicit none   character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back. integer ln, cn # The line and column nos. returned.   integer chr(CHRSZ)   call getchr (line, linno, colno, pushbk, npshbk, chr) ln = chr(ILINNO) cn = chr(ICOLNO) call pshchr (pushbk, npshbk, chr) end   #---------------------------------------------------------------------   function isspc (c)   # Is c character code for a space?   implicit none   integer c logical isspc   # # The following is correct for ASCII: 32 is the SPACE character, and # 9 to 13 are control characters commonly regarded as spaces. # # In Unicode these are all code points for spaces, but so are others # besides. # isspc = (c == 32 || (9 <= c && c <= 13)) end   function isdgt (c)   # Is c character code for a digit?   implicit none   integer c logical isdgt   isdgt = (ichar ('0') <= c && c <= ichar ('9')) end   function isalph (c)   # Is c character code for a letter?   implicit none   integer c logical isalph   # # The following is correct for ASCII and Unicode, but not for # EBCDIC. # isalph = (ichar ('a') <= c && c <= ichar ('z')) _ || (ichar ('A') <= c && c <= ichar ('Z')) end   function isid0 (c)   # Is c character code for the start of an identifier?   implicit none   integer c logical isid0   logical isalph   isid0 = isalph (c) || c == ichar ('_') end   function isid1 (c)   # Is c character code for the continuation of an identifier?   implicit none   integer c logical isid1   logical isalph logical isdgt   isid1 = isalph (c) || isdgt (c) || c == ichar ('_') end   #---------------------------------------------------------------------   function trimlf (str, n)   # "Trim left" leading spaces.   implicit none   character str(*) # The string to "trim". integer n # The length. integer trimlf # The index of the first non-space # character, or n + 1.   logical isspc   integer j logical done   j = 1 done = .false. while (!done) { if (j == n + 1) done = .true. else if (!isspc (ichar (str(j)))) done = .true. else j = j + 1 } trimlf = j end   function trimrt (str, n)   # "Trim right" trailing spaces.   implicit none   character str(*) # The string to "trim". integer n # The length including trailing spaces. integer trimrt # The length without trailing spaces.   logical isspc   integer j logical done   j = n done = .false. while (!done) { if (j == 0) done = .true. else if (!isspc (ichar (str(j)))) done = .true. else j = j - 1 } trimrt = j end   #---------------------------------------------------------------------   subroutine toknam (tokno, str, i)   # Copy a token name to the character array str, starting at i.   implicit none   integer tokno character str(*) integer i integer j   character*16 names(0:30) character*16 nm   data names / "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 " /   nm = names(tokno) for (j = 0; j < 16; j = j + 1) str(i + j) = nm(1 + j : 1 + j) end   subroutine intstr (str, i, n, x)   # Convert a positive integer to a substring.   implicit none   character str(*) # Destination string. integer i, n # Index and length of the field. integer x # The positive integer to represent.   integer j integer y   if (x == 0) { for (j = 0; j < n - 1; j = j + 1) str(i + j) = ' ' str(i + j) = '0' } else { y = x for (j = n - 1; 0 <= j; j = j - 1) { if (y == 0) str(i + j) = ' ' else { str(i + j) = char (mod (y, 10) + ichar ('0')) y = y / 10 } } } end   subroutine prttok (strngs, tok)   # Print a token.   implicit none   character strngs(STRNSZ) # String pool. integer tok(TOKSZ) # The token.   integer trimrt   character line(OUTLSZ) character*20 fmt integer i, n integer tokno   for (i = 1; i <= OUTLSZ; i = i + 1) line(i) = ' '   call intstr (line, 1, 10, tok(ILINNO)) call intstr (line, 12, 10, tok(ICOLNO))   tokno = tok(ITOKNO) call toknam (tokno, line, 25) if (tokno == TKID || tokno == TKINT || tokno == TKSTR) { i = tok(IARGIX) n = tok(IARGLN) call cpystr (strngs, i, n, line, 45) }   n = trimrt (line, OUTLSZ) write (fmt, '(''('', I10, ''A)'')') n write (*, fmt) (line(i), i = 1, n) end   #---------------------------------------------------------------------   subroutine wrtpos (ln, cn)   implicit none   integer ln, cn   write (*, 1000) ln, cn 1000 format ('At line ', I5, ', column ' I5) end   #---------------------------------------------------------------------   subroutine utcmnt (ln, cn)   implicit none   integer ln, cn   call wrtpos (ln, cn) write (*, '(''Unterminated comment'')') stop end   subroutine skpcmt (line, linno, colno, pushbk, npshbk, ln, cn)   # Skip to the end of a comment.   implicit none   character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back. integer ln, cn # Line and column of start of comment.   integer chr(CHRSZ) logical done   done = .false. while (!done) { call getchr (line, linno, colno, pushbk, npshbk, chr) if (chr(ICHRCD) == ichar ('*')) { call getchr (line, linno, colno, pushbk, npshbk, chr) if (chr(ICHRCD) == ichar ('/')) done = .true. else if (chr(ICHRCD) == EOF) call utcmnt (ln, cn) } else if (chr(ICHRCD) == EOF) call utcmnt (ln, cn) } end   subroutine skpspc (line, linno, colno, pushbk, npshbk)   # Skip spaces and comments.   implicit none   character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back.   logical isspc   integer chr(CHRSZ) integer chr1(CHRSZ) integer ln, cn logical done   done = .false. while (!done) { call getchr (line, linno, colno, pushbk, npshbk, chr) if (!isspc (chr(ICHRCD))) { if (chr(ICHRCD) != ichar ('/')) { call pshchr (pushbk, npshbk, chr) done = .true. } else { call getchr (line, linno, colno, pushbk, npshbk, chr1) if (chr1(ICHRCD) != ichar ('*')) { call pshchr (pushbk, npshbk, chr1) call pshchr (pushbk, npshbk, chr) done = .true. } else { ln = chr(ILINNO) cn = chr(ICOLNO) call skpcmt (line, linno, colno, pushbk, npshbk, _ ln, cn) } } } } end   #---------------------------------------------------------------------   subroutine rwdlkp (strngs, istrng, src, i0, n0, ln, cn, tok)   # Reserved word lookup   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character src(*) # The source string. integer i0, n0 # Index and length of the substring. integer ln, cn # Line and column number # to associate with the token. integer tok(TOKSZ) # The output token.   integer tokno integer i, n   tokno = TKID   if (n0 == 2) { if (src(i0) == 'i' && src(i0 + 1) == 'f') tokno = TKIF } else if (n0 == 4) { if (src(i0) == 'e' && src(i0 + 1) == 'l' _ && src(i0 + 2) == 's' && src(i0 + 3) == 'e') tokno = TKELSE else if (src(i0) == 'p' && src(i0 + 1) == 'u' _ && src(i0 + 2) == 't' && src(i0 + 3) == 'c') tokno = TKPUTC } else if (n0 == 5) { if (src(i0) == 'p' && src(i0 + 1) == 'r' _ && src(i0 + 2) == 'i' && src(i0 + 3) == 'n' _ && src(i0 + 4) == 't') tokno = TKPRNT else if (src(i0) == 'w' && src(i0 + 1) == 'h' _ && src(i0 + 2) == 'i' && src(i0 + 3) == 'l' _ && src(i0 + 4) == 'e') tokno = TKWHIL }   i = 0 n = 0 if (tokno == TKID) call addstr (strngs, istrng, src, i0, n0, i, n)   tok(ITOKNO) = tokno tok(IARGIX) = i tok(IARGLN) = n tok(ILINNO) = ln tok(ICOLNO) = cn end   subroutine scnwrd (line, linno, colno, pushbk, npshbk, ln, cn, buf, n)   # Scan characters that may represent an identifier, reserved word, # or integer literal.   implicit none   character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back. integer ln, cn # Line and column number of the start. character buf(LINESZ) # The output buffer. integer n # The length of the string collected.   logical isid1   integer chr(CHRSZ)   n = 0 call getchr (line, linno, colno, pushbk, npshbk, chr) ln = chr(ILINNO) cn = chr(ICOLNO) while (isid1 (chr(ICHRCD))) { n = n + 1 buf(n) = char (chr(ICHRCD)) call getchr (line, linno, colno, pushbk, npshbk, chr) } call pshchr (pushbk, npshbk, chr) end   subroutine scnidr (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok)   # Scan an identifier or reserved word.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back. integer ln, cn # Line and column number of the start. integer tok(TOKSZ) # The output token.   character buf(LINESZ) integer n   call scnwrd (line, linno, colno, pushbk, npshbk, ln, cn, buf, n) call rwdlkp (strngs, istrng, buf, 1, n, ln, cn, tok) end   subroutine scnint (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok)   # Scan a positive integer literal.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back. integer ln, cn # Line and column number of the start. integer tok(TOKSZ) # The output token.   logical isdgt   character buf(LINESZ) integer n0, n integer i, j, k character*80 fmt   call scnwrd (line, linno, colno, pushbk, npshbk, ln, cn, buf, n0) for (j = 1; j <= n0; j = j + 1) if (!isdgt (ichar (buf(j)))) { call wrtpos (ln, cn) write (fmt, 1000) n0 1000 format ('(''Not a legal word: "''', I10, 'A, ''"'')') write (*, fmt) (buf(k), k = 1, n0) stop }   call addstr (strngs, istrng, buf, 1, n0, i, n)   tok(ITOKNO) = TKINT tok(IARGIX) = i tok(IARGLN) = n tok(ILINNO) = ln tok(ICOLNO) = cn end   subroutine utclit (ln, cn)   implicit none   integer ln, cn   call wrtpos (ln, cn) write (*, '(''Unterminated character literal'')') stop end   subroutine scnch1 (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok)   # Scan a character literal, without yet checking that the literal # ends correctly.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back. integer tok(TOKSZ) # The output token.   integer trimlf   integer bufsz parameter (bufsz = 40)   integer chr(CHRSZ) integer chr1(CHRSZ) integer chr2(CHRSZ) integer ln, cn character buf(bufsz) integer i, j, n   # Refetch the opening quote. call getchr (line, linno, colno, pushbk, npshbk, chr) ln = chr(ILINNO) cn = chr(ICOLNO)   tok(ITOKNO) = TKINT tok(ILINNO) = ln tok(ICOLNO) = cn   call getchr (line, linno, colno, pushbk, npshbk, chr1) if (chr1(ICHRCD) == EOF) call utclit (ln, cn) if (chr1(ICHRCD) == BACKSL) { call getchr (line, linno, colno, pushbk, npshbk, chr2) if (chr2(ICHRCD) == EOF) call utclit (ln, cn) else if (chr2(ICHRCD) == ichar ('n')) { tok(IARGIX) = LOC10 # "10" = code for Unix newline tok(IARGLN) = 2 } else if (chr2(ICHRCD) == BACKSL) { tok(IARGIX) = LOC92 # "92" = code for backslash tok(IARGLN) = 2 } else { call wrtpos (ln, cn) write (*, '(''Unsupported escape: '', 1A)') _ char (chr2(ICHRCD)) stop } } else { # Character codes are non-negative, so we can use intstr. call intstr (buf, 1, bufsz, chr1(ICHRCD))   j = trimlf (buf, bufsz) call addstr (strngs, istrng, buf, j, bufsz - (j - 1), i, n) tok(IARGIX) = i tok(IARGLN) = n } end   subroutine scnch (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok)   # Scan a character literal.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back. integer tok(TOKSZ) # The output token.   integer ln, cn integer chr(CHRSZ)   call getpos (line, linno, colno, pushbk, npshbk, ln, cn) call scnch1 (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok) call getchr (line, linno, colno, pushbk, npshbk, chr) if (chr(ICHRCD) != ichar ('''')) { while (.true.) { if (chr(ICHRCD) == EOF) { call utclit (ln, cn) stop } else if (chr(ICHRCD) == ichar ('''')) { call wrtpos (ln, cn) write (*, '(''Unsupported multicharacter literal'')') stop } call getchr (line, linno, colno, pushbk, npshbk, chr) } } end   subroutine scnstr (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok)   # Scan a string literal.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back. integer tok(TOKSZ) # The output token.   integer ln, cn integer chr1(CHRSZ) integer chr2(CHRSZ) character buf(LINESZ + 10) # Enough space, with some room to spare. integer n0 integer i, n   call getchr (line, linno, colno, pushbk, npshbk, chr1) ln = chr1(ILINNO) cn = chr1(ICOLNO)   tok(ITOKNO) = TKSTR tok(ILINNO) = ln tok(ICOLNO) = cn   n0 = 1 buf(n0) = '"'   call getchr (line, linno, colno, pushbk, npshbk, chr1) while (chr1(ICHRCD) != ichar ('"')) { # Our input method always puts a NEWLIN before EOF, and so this # test is redundant, unless someone changes the input method. if (chr1(ICHRCD) == EOF || chr1(ICHRCD) == NEWLIN) { call wrtpos (ln, cn) write (*, '(''Unterminated string literal'')') stop } if (chr1(ICHRCD) == BACKSL) { call getchr (line, linno, colno, pushbk, npshbk, chr2) if (chr2(ICHRCD) == ichar ('n')) { n0 = n0 + 1 buf(n0) = char (BACKSL) n0 = n0 + 1 buf(n0) = 'n' } else if (chr2(ICHRCD) == BACKSL) { n0 = n0 + 1 buf(n0) = char (BACKSL) n0 = n0 + 1 buf(n0) = char (BACKSL) } else { call wrtpos (chr1(ILINNO), chr1(ICOLNO)) write (*, '(''Unsupported escape sequence'')') stop } } else { n0 = n0 + 1 buf(n0) = char (chr1(ICHRCD)) } call getchr (line, linno, colno, pushbk, npshbk, chr1) } n0 = n0 + 1 buf(n0) = '"'   call addstr (strngs, istrng, buf, 1, n0, i, n) tok(IARGIX) = i tok(IARGLN) = n end   subroutine unxchr (chr)   implicit none   integer chr(CHRSZ)   call wrtpos (chr(ILINNO), chr(ICOLNO)) write (*, 1000) char (chr(ICHRCD)) 1000 format ('Unexpected character ''', A1, '''') stop end   subroutine scntok (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok)   # Scan a token.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back. integer tok(TOKSZ) # The output token.   logical isdgt logical isid0   integer chr(CHRSZ) integer chr1(CHRSZ) integer ln, cn   call getchr (line, linno, colno, pushbk, npshbk, chr) ln = chr(ILINNO) cn = chr(ICOLNO) tok(ILINNO) = ln tok(ICOLNO) = cn tok(IARGIX) = 0 tok(IARGLN) = 0 if (chr(ICHRCD) == ichar (',')) tok(ITOKNO) = TKCMMA else if (chr(ICHRCD) == ichar (';')) tok(ITOKNO) = TKSEMI else if (chr(ICHRCD) == ichar ('(')) tok(ITOKNO) = TKLPAR else if (chr(ICHRCD) == ichar (')')) tok(ITOKNO) = TKRPAR else if (chr(ICHRCD) == ichar ('{')) tok(ITOKNO) = TKLBRC else if (chr(ICHRCD) == ichar ('}')) tok(ITOKNO) = TKRBRC else if (chr(ICHRCD) == ichar ('*')) tok(ITOKNO) = TKMUL else if (chr(ICHRCD) == ichar ('/')) tok(ITOKNO) = TKDIV else if (chr(ICHRCD) == ichar ('%')) tok(ITOKNO) = TKMOD else if (chr(ICHRCD) == ichar ('+')) tok(ITOKNO) = TKADD else if (chr(ICHRCD) == ichar ('-')) tok(ITOKNO) = TKSUB else if (chr(ICHRCD) == ichar ('<')) { call getchr (line, linno, colno, pushbk, npshbk, chr1) if (chr1(ICHRCD) == ichar ('=')) tok(ITOKNO) = TKLE else { call pshchr (pushbk, npshbk, chr1) tok(ITOKNO) = TKLT } } else if (chr(ICHRCD) == ichar ('>')) { call getchr (line, linno, colno, pushbk, npshbk, chr1) if (chr1(ICHRCD) == ichar ('=')) tok(ITOKNO) = TKGE else { call pshchr (pushbk, npshbk, chr1) tok(ITOKNO) = TKGT } } else if (chr(ICHRCD) == ichar ('=')) { call getchr (line, linno, colno, pushbk, npshbk, chr1) if (chr1(ICHRCD) == ichar ('=')) tok(ITOKNO) = TKEQ else { call pshchr (pushbk, npshbk, chr1) tok(ITOKNO) = TKASGN } } else if (chr(ICHRCD) == ichar ('!')) { call getchr (line, linno, colno, pushbk, npshbk, chr1) if (chr1(ICHRCD) == ichar ('=')) tok(ITOKNO) = TKNE else { call pshchr (pushbk, npshbk, chr1) tok(ITOKNO) = TKNOT } } else if (chr(ICHRCD) == ichar ('&')) { call getchr (line, linno, colno, pushbk, npshbk, chr1) if (chr1(ICHRCD) == ichar ('&')) tok(ITOKNO) = TKAND else call unxchr (chr) } else if (chr(ICHRCD) == ichar ('|')) { call getchr (line, linno, colno, pushbk, npshbk, chr1) if (chr1(ICHRCD) == ichar ('|')) tok(ITOKNO) = TKOR else call unxchr (chr) } else if (chr(ICHRCD) == ichar ('"')) { call pshchr (pushbk, npshbk, chr) call scnstr (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok) } else if (chr(ICHRCD) == ichar ('''')) { call pshchr (pushbk, npshbk, chr) call scnch (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok) } else if (isdgt (chr(ICHRCD))) { call pshchr (pushbk, npshbk, chr) call scnint (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok) } else if (isid0 (chr(ICHRCD))) { call pshchr (pushbk, npshbk, chr) call scnidr (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok) } else call unxchr (chr) end   subroutine scntxt (strngs, istrng, _ line, linno, colno, pushbk, npshbk)   # Scan the text and print the token stream.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back.   integer chr(CHRSZ) integer tok(TOKSZ)   chr(ICHRCD) = ichar ('x') while (chr(ICHRCD) != EOF) { call skpspc (line, linno, colno, pushbk, npshbk) call getchr (line, linno, colno, pushbk, npshbk, chr) if (chr(ICHRCD) != EOF) { call pshchr (pushbk, npshbk, chr) call scntok (strngs, istrng, _ line, linno, colno, pushbk, npshbk, _ tok) call prttok (strngs, tok) } } tok(ITOKNO) = TKEOI tok(ILINNO) = chr(ILINNO) tok(ICOLNO) = chr(ICOLNO) tok(IARGIX) = 0 tok(IARGLN) = 0 call prttok (strngs, tok) end   #---------------------------------------------------------------------   program lex   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character line(LINESZ) # Input buffer. integer linno, colno # Current line and column numbers. integer pushbk(CHRSZ, PSHBSZ) # Pushback buffer. integer npshbk # Number of characters pushed back.   integer i, n   istrng = 1   # Locate "10" (newline) at 1 in the string pool. line(1) = '1' line(2) = '0' call addstr (strngs, istrng, line, 1, 2, i, n) if (i != 1 && n != 2) { write (*, '(''internal error'')') stop }   # Locate "92" (backslash) at 3 in the string pool. line(1) = '9' line(2) = '2' call addstr (strngs, istrng, line, 1, 2, i, n) if (i != 3 && n != 2) { write (*, '(''internal error'')') stop }   linno = 0 colno = LINESZ + 1 # This will trigger a READ. npshbk = 0   call scntxt (strngs, istrng, line, linno, colno, pushbk, npshbk) end   ######################################################################
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"
#Oforth
Oforth
System.Args println
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"
#Oz
Oz
functor import Application System define ArgList = {Application.getArgs plain} {ForAll ArgList System.showInfo} {Application.exit 0} end
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.)
#F.23
F#
// this comments to the end of the line (* this comments a region which can be multi-line *)
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.)
#Factor
Factor
! Comments starts with "! " #! Or with "#! " ! and last until the end of the line   USE: multiline /* The multiline vocabulary implements C-like multiline comments. */
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.
#M2000_Interpreter
M2000 Interpreter
  Module Life { Font "courier new" Form 40, 18 Cls 3,0 Double Report 2, "Game of Life" Normal Cls 5, 2 Const Mx=20, My=10 Dim A(0 to Mx+1, 0 to My+1)=0 Flush REM Data (2,2),(2,3),(3,3),(4,3),(5,4),(,3,4),(5,3),(6,2),(8,5),(5,8) Data (5,3) Data (5,4) Data (5,5) generation=1 While not empty (A, B)=Array A(A,B)=1 End While Display() Do k$=Key$ If k$=chr$(13) Then exit A()=@GetNext() refresh 500 Display() Until A()#Sum()=0 K$=Key$ Cls, 0 End Function GetNext() Local B() B()=A() ' copy array Local B=B() ' get a pointer B*=0 ' make all element zero Local i, j, tot For j=1 to My For i=1 to Mx tot=-A(i,j) For k=j-1 to j+1 For m=i-1 to i+1 tot+=A(m, k) Next Next If A(i,j)=1 Then If tot=2 or tot=3 Then B(i,j)=1 Else.if tot=3 Then B(i,j)=1 End If Next Next =B() End Function Sub Display() Cursor 0,2 move ! ' move graphic to character cursor Fill scale.x, scale.y-pos.Y, 1, 5 Print "Generation:";Generation Generation++ Local i, j For j=1 to My Print @(width div 2-Mx div 2); For i=1 to Mx Print If$(A(I,J)=1->"■", "□"); Next Print Next Print Report 2, "Press enter to exit or any other key for Next generation" End Sub   } Life  
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.
#EasyLang
EasyLang
i = random 10 if i mod 2 = 0 print i & " is divisible by 2" elif i mod 3 = 0 print i & " is divisible by 3" else print i & " is not divisible by 2 or 3" .
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
#Scheme
Scheme
  (define (compare-strings fn strs) (or (null? strs) ; returns #t on empty list (null? (cdr strs)) ; returns #t on list of size 1 (do ((fst strs (cdr fst)) (snd (cdr strs) (cdr snd))) ((or (null? snd) (not (fn (car fst) (car snd)))) (null? snd))))) ; returns #t if the snd list is empty, meaning all comparisons are exhausted   (compare-strings string=? strings) ; test for all equal (compare-strings string<? strings) ; test for in ascending order  
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const func boolean: allTheSame (in array string: strings) is func result var boolean: allTheSame is TRUE; local var integer: index is 0; begin for index range 2 to length(strings) until not allTheSame do if strings[pred(index)] <> strings[index] then allTheSame := FALSE; end if; end for; end func;   const func boolean: strictlyAscending (in array string: strings) is func result var boolean: strictlyAscending is TRUE; local var integer: index is 0; begin for index range 2 to length(strings) until not strictlyAscending do if strings[pred(index)] >= strings[index] then strictlyAscending := FALSE; end if; end for; end func;
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.
#MAXScript
MAXScript
  fn separate words: = ( if words == unsupplied or words == undefined or classof words != array then return "{}" else ( local toReturn = "{" local pos = 1 while pos <= words.count do ( if pos == 1 then (append toReturn words[pos]; pos+=1) else ( if pos <= words.count-1 then (append toReturn (", "+words[pos]); pos+=1) else ( append toReturn (" and " + words[pos]) pos +=1 ) ) ) return (toReturn+"}") ) )  
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method quibble(arg) public static parse arg '[' lst ']' lst = lst.changestr('"', '').space(1) lc = lst.lastpos(',') if lc > 0 then lst = lst.insert('and', lc).overlay(' ', lc) return '{'lst'}'   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static lists = ['[]', - -- {} '["ABC"]', - -- {ABC} '["ABC", "DEF"]', - -- {ABC and DEF} '["ABC", "DEF", "G", "H"]'] -- {ABC, DEF, G and H} loop lst over lists say lst.right(30) ':' quibble(lst) end lst return  
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
#Scheme
Scheme
(define (combs-with-rep k lst) (cond ((= k 0) '(())) ((null? lst) '()) (else (append (map (lambda (x) (cons (car lst) x)) (combs-with-rep (- k 1) lst)) (combs-with-rep k (cdr lst))))))   (display (combs-with-rep 2 (list "iced" "jam" "plain"))) (newline) (display (length (combs-with-rep 3 '(1 2 3 4 5 6 7 8 9 10)))) (newline)
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
#Scala
Scala
  package xyz.hyperreal.rosettacodeCompiler   import scala.io.Source import scala.util.matching.Regex   object LexicalAnalyzer { private val EOT = '\u0004'   val symbols = Map( "*" -> "Op_multiply", "/" -> "Op_divide", "%" -> "Op_mod", "+" -> "Op_add", "-" -> "Op_minus", "<" -> "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" )   val keywords = Map( "if" -> "Keyword_if", "else" -> "Keyword_else", "while" -> "Keyword_while", "print" -> "Keyword_print", "putc" -> "Keyword_putc" ) val alpha = ('a' to 'z' toSet) ++ ('A' to 'Z') val numeric = '0' to '9' toSet val alphanumeric = alpha ++ numeric val identifiers = StartRestToken("Identifier", alpha + '_', alphanumeric + '_') val integers = SimpleToken("Integer", numeric, alpha, "alpha characters may not follow right after a number")   val characters = DelimitedToken("Integer", '\'', "[^'\\n]|\\\\n|\\\\\\\\" r, "invalid character literal", "unclosed character literal")   val strings = DelimitedToken("String", '"', "[^\"\\n]*" r, "invalid string literal", "unclosed string literal")   def apply = new LexicalAnalyzer(4, symbols, keywords, "End_of_input", identifiers, integers, characters, strings)   abstract class Token case class StartRestToken(name: String, start: Set[Char], rest: Set[Char]) extends Token case class SimpleToken(name: String, chars: Set[Char], exclude: Set[Char], excludeError: String) extends Token case class DelimitedToken(name: String, delimiter: Char, pattern: Regex, patternError: String, unclosedError: String) extends Token }   class LexicalAnalyzer(tabs: Int, symbols: Map[String, String], keywords: Map[String, String], endOfInput: String, identifier: LexicalAnalyzer.Token, tokens: LexicalAnalyzer.Token*) {   import LexicalAnalyzer._   private val symbolStartChars = symbols.keys map (_.head) toSet private val symbolChars = symbols.keys flatMap (_.toList) toSet private var curline: Int = _ private var curcol: Int = _   def fromStdin = fromSource(Source.stdin)   def fromString(src: String) = fromSource(Source.fromString(src))   def fromSource(ast: Source) = { curline = 1 curcol = 1   var s = (ast ++ Iterator(EOT)) map (new Chr(_)) toStream   tokenize   def token(name: String, first: Chr) = println(f"${first.line}%5d ${first.col}%6d $name")   def value(name: String, v: String, first: Chr) = println(f"${first.line}%5d ${first.col}%6d $name%-14s $v")   def until(c: Char) = { val buf = new StringBuilder   def until: String = if (s.head.c == EOT || s.head.c == c) buf.toString else { buf += getch until }   until }   def next = s = s.tail   def getch = { val c = s.head.c   next c }   def consume(first: Char, cs: Set[Char]) = { val buf = new StringBuilder   def consume: String = if (s.head.c == EOT || !cs(s.head.c)) buf.toString else { buf += getch consume }   buf += first consume }   def comment(start: Chr): Unit = { until('*')   if (s.head.c == EOT || s.tail.head.c == EOT) sys.error(s"unclosed comment ${start.at}") else if (s.tail.head.c != '/') { next comment(start) } else { next next } }   def recognize(t: Token): Option[(String, String)] = { val first = s   next   t match { case StartRestToken(name, start, rest) => if (start(first.head.c)) Some((name, consume(first.head.c, rest))) else { s = first None } case SimpleToken(name, chars, exclude, excludeError) => if (chars(first.head.c)) { val m = consume(first.head.c, chars)   if (exclude(s.head.c)) sys.error(s"$excludeError ${s.head.at}") else Some((name, m)) } else { s = first None } case DelimitedToken(name, delimiter, pattern, patternError, unclosedError) => if (first.head.c == delimiter) { val m = until(delimiter)   if (s.head.c != delimiter) sys.error(s"$unclosedError ${first.head.at}") else if (pattern.pattern.matcher(m).matches) { next Some((name, s"$delimiter$m$delimiter")) } else sys.error(s"$patternError ${s.head.at}") } else { s = first None } } }   def tokenize: Unit = if (s.head.c == EOT) token(endOfInput, s.head) else { if (s.head.c.isWhitespace) next else if (s.head.c == '/' && s.tail.head.c == '*') comment(s.head) else if (symbolStartChars(s.head.c)) { val first = s.head val buf = new StringBuilder   while (!symbols.contains(buf.toString) && s.head.c != EOT && symbolChars(s.head.c)) buf += getch   while (symbols.contains(buf.toString :+ s.head.c) && s.head.c != EOT && symbolChars(s.head.c)) buf += getch   symbols get buf.toString match { case Some(name) => token(name, first) case None => sys.error(s"unrecognized symbol: '${buf.toString}' ${first.at}") } } else { val first = s.head   recognize(identifier) match { case None => find(0)   @scala.annotation.tailrec def find(t: Int): Unit = if (t == tokens.length) sys.error(s"unrecognized character ${first.at}") else recognize(tokens(t)) match { case None => find(t + 1) case Some((name, v)) => value(name, v, first) } case Some((name, ident)) => keywords get ident match { case None => value(name, ident, first) case Some(keyword) => token(keyword, first) } } }   tokenize } }   private class Chr(val c: Char) { val line = curline val col = curcol   if (c == '\n') { curline += 1 curcol = 1 } else if (c == '\r') curcol = 1 else if (c == '\t') curcol += tabs - (curcol - 1) % tabs else curcol += 1   def at = s"[${line}, ${col}]"   override def toString: String = s"<$c, $line, $col>" }   }  
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"
#Pascal
Pascal
my @params = @ARGV; my $params_size = @ARGV; my $second = $ARGV[1]; my $fifth = $ARGV[4];
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"
#Perl
Perl
my @params = @ARGV; my $params_size = @ARGV; my $second = $ARGV[1]; my $fifth = $ARGV[4];
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.)
#Falcon
Falcon
  /* Start comment block My Life Story */   // set up my bank account total bank_account_total = 1000000 // Wish this was the case  
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.)
#FALSE
FALSE
{comments are in curly braces}
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.
#MANOOL
MANOOL
  { {extern "manool.org.18/std/0.3/all"} in : let { N = 40; M = 80 } in : let { G = 99 } in : let { Display = { proc { B } as  : for { I = Range[N]$ } do  : do Out.WriteLine[] after  : for { J = Range[M]$ } do Out.Write[{if B[I; J] <> 0 then "*" else " "}] } } in : var { B = {array N of: array M of 0} } in -- initialization B[19; 41] = 1 B[20; 40] = 1 B[21; 40] = 1 B[22; 40] = 1 B[22; 41] = 1 B[22; 42] = 1 B[22; 43] = 1 B[19; 44] = 1 -- end of initialization Out.WriteLine["Before:"]; Display[B] { var { NextB = B } in  : repeat G do  : do {assign B = NextB; NextB = B} after  : for { I = Range[N]$ } do  : var { Up = (I - 1).Mod[N]; Down = (I + 1).Mod[N] } in  : for { J = Range[M]$ } do  : var { Left = (J - 1).Mod[M]; Right = (J + 1).Mod[M] } in  : var { Count = B[Up  ; Left ] + B[Up  ; J ] + B[Up  ; Right] + B[I  ; Right] + B[Down; Right] + B[Down; J ] + B[Down; Left ] + B[I  ; Left ] } in NextB[I; J] = { if Count == 2 then B[I; J] else  : if Count == 3 then 1 else 0 } } Out.WriteLine["After " G " generations:"]; Display[B] }  
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.
#Efene
Efene
  show_if_with_parenthesis = fn (Num) { if (Num == 1) { io.format("is one~n") } else if (Num === 2) { io.format("is two~n") } else { io.format("not one not two~n") } }   show_if_without_parenthesis = fn (Num) { if Num == 1 { io.format("is one~n") } else if Num === 2 { io.format("is two~n") } else { io.format("not one not two~n") } }   show_switch_with_parenthesis = fn (Num) { switch (Num) { case (1) { io.format("one!~n") } case (2) { io.format("two!~n") } else { io.format("else~n") } } }   show_switch_without_parenthesis = fn (Num) { switch (Num) { case 1 { io.format("one!~n") } case 2 { io.format("two!~n") } else { io.format("else~n") } } }   @public run = fn () { show_if_with_parenthesis(random.uniform(3)) show_if_without_parenthesis(random.uniform(3))   show_switch_with_parenthesis(random.uniform(3)) show_switch_without_parenthesis(random.uniform(3)) }
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
#SenseTalk
SenseTalk
analyze ["AA","BB","CC"] analyze ["AA","AA","AA"] analyze ["AA","CC","BB"] analyze ["AA","ACB","BB","CC"] analyze ["single_element"]   to analyze aList put "List: " & aList put " " & (if allEqual(aList) then "IS" else "Is NOT") && "all equal" put " " & (if isAscending(aList) then "IS" else "Is NOT") && "strictly ascending" end analyze   to handle allEqual strings return the number of items in the unique items of strings is less than 2 end allEqual   to handle isAscending strings repeat with n = 2 to the number of items in strings if item n of strings isn't more than item n-1 of strings then return False end if end repeat return True end isAscending
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
#Sidef
Sidef
1..arr.end -> all{ arr[0] == arr[_] } # all equal 1..arr.end -> all{ arr[_-1] < arr[_] } # strictly ascending
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.
#Nim
Nim
proc commaQuibble(s: openArray[string]): string = result = "" for i, c in s: if i > 0: result.add (if i < s.high: ", " else: " and ") result.add c result = "{" & result & "}"   var s = @[@[], @["ABC"], @["ABC", "DEF"], @["ABC", "DEF", "G", "H"]] for i in s: echo commaQuibble(i)
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
#Sidef
Sidef
func cwr (n, l, a = []) { n>0 ? (^l -> map {|k| __FUNC__(n-1, l.slice(k), [a..., l[k]]) }) : a }   cwr(2, %w(iced jam plain)).each {|a| say a.map{ .join(' ') }.join("\n") }
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is 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
#Scheme
Scheme
  (import (scheme base) (scheme char) (scheme file) (scheme process-context) (scheme write))   (define *symbols* (list (cons #\( 'LeftParen) (cons #\) 'RightParen) (cons #\{ 'LeftBrace) (cons #\} 'RightBrace) (cons #\; 'Semicolon) (cons #\, 'Comma) (cons #\* 'Op_multiply) (cons #\/ 'Op_divide) (cons #\% 'Op_mod) (cons #\+ 'Op_add) (cons #\- 'Op_subtract)))   (define *keywords* (list (cons 'if 'Keyword_if) (cons 'else 'Keyword_else) (cons 'while 'Keyword_while) (cons 'print 'Keyword_print) (cons 'putc 'Keyword_putc)))   ;; return list of tokens from current port (define (read-tokens) ; information on position in input (define line 1) (define col 0) (define next-char #f) ; get char, updating line/col posn (define (get-next-char) (if (char? next-char) ; check for returned character (let ((c next-char)) (set! next-char #f) c) (let ((c (read-char))) (cond ((and (not (eof-object? c)) (char=? c #\newline)) (set! col 0) (set! line (+ 1 line)) (get-next-char)) (else (set! col (+ 1 col)) c))))) (define (push-char c) (set! next-char c)) ; step over any whitespace or comments (define (skip-whitespace+comment) (let loop () (let ((c (get-next-char))) (cond ((eof-object? c) '()) ((char-whitespace? c) ; ignore whitespace (loop)) ((char=? c #\/) ; check for comments (if (char=? (peek-char) #\*) ; found start of comment (begin ; eat comment (get-next-char) (let m ((c (get-next-char))) (cond ((eof-object? c) (error "End of file in comment")) ((and (char=? c #\*) (char=? (peek-char) #\/)) (get-next-char)) ; eat / and end (else (m (get-next-char))))) (loop)) ; continue looking for whitespace / more comments (push-char #\/))) ; not comment, so put / back and return (else ; return to stream, as not a comment or space char (push-char c)))))) ; read next token from input (define (next-token) (define (read-string) ; returns string value along with " " marks (let loop ((chars '(#\"))) ; " (needed to appease Rosetta code's highlighter) (cond ((eof-object? (peek-char)) (error "End of file while scanning string literal.")) ((char=? (peek-char) #\newline) (error "End of line while scanning string literal.")) ((char=? (peek-char) #\") ; " (get-next-char) ; consume the final quote (list->string (reverse (cons #\" chars)))) ; " highlighter) (else (loop (cons (get-next-char) chars)))))) (define (read-identifier initial-c) ; returns identifier as a Scheme symbol (do ((chars (list initial-c) (cons c chars)) (c (get-next-char) (get-next-char))) ((or (eof-object? c) ; finish when hit end of file (not (or (char-numeric? c) ; or a character not permitted in an identifier (char-alphabetic? c) (char=? c #\_)))) (push-char c) ; return last character to stream (string->symbol (list->string (reverse chars)))))) (define (read-number initial-c) ; returns integer read as a Scheme integer (let loop ((res (digit-value initial-c)) (c (get-next-char))) (cond ((char-alphabetic? c) (error "Invalid number - ends in alphabetic chars")) ((char-numeric? c) (loop (+ (* res 10) (digit-value c)) (get-next-char))) (else (push-char c) ; return non-number to stream res)))) ; select op symbol based on if there is a following = sign (define (check-eq-extend start-line start-col opeq op) (if (char=? (peek-char) #\=) (begin (get-next-char) ; consume it (list start-line start-col opeq)) (list start-line start-col op))) ; (let* ((start-line line) ; save start position of tokens (start-col col) (c (get-next-char))) (cond ((eof-object? c) (list start-line start-col 'End_of_input)) ((char-alphabetic? c) ; read an identifier (let ((id (read-identifier c))) (if (assq id *keywords*) ; check if identifier is a keyword (list start-line start-col (cdr (assq id *keywords*))) (list start-line start-col 'Identifier id)))) ((char-numeric? c) ; read a number (list start-line start-col 'Integer (read-number c))) (else (case c ((#\( #\) #\{ #\} #\; #\, #\* #\/ #\% #\+ #\-) (list start-line start-col (cdr (assq c *symbols*)))) ((#\<) (check-eq-extend start-line start-col 'Op_lessequal 'Op_less)) ((#\>) (check-eq-extend start-line start-col 'Op_greaterequal 'Op_greater)) ((#\=) (check-eq-extend start-line start-col 'Op_equal 'Op_assign)) ((#\!) (check-eq-extend start-line start-col 'Op_notequal 'Op_not)) ((#\& #\|) (if (char=? (peek-char) c) ; looks for && or || (begin (get-next-char) ; consume second character if valid (list start-line start-col (if (char=? c #\&) 'Op_and 'Op_or))) (push-char c))) ((#\") ; " (list start-line start-col 'String (read-string))) ((#\') (let* ((c1 (get-next-char)) (c2 (get-next-char))) (cond ((or (eof-object? c1) (eof-object? c2)) (error "Incomplete character constant")) ((char=? c1 #\') (error "Empty character constant")) ((and (char=? c2 #\') ; case of single character (not (char=? c1 #\\))) (list start-line start-col 'Integer (char->integer c1))) ((and (char=? c1 #\\) ; case of escaped character (char=? (peek-char) #\')) (get-next-char) ; consume the ending ' (cond ((char=? c2 #\n) (list start-line start-col 'Integer 10)) ((char=? c2 #\\) (list start-line start-col 'Integer (char->integer c2))) (else (error "Unknown escape sequence")))) (else (error "Multi-character constant"))))) (else (error "Unrecognised character"))))))) ; (let loop ((tokens '())) ; loop, ignoring space/comments, while reading tokens (skip-whitespace+comment) (let ((tok (next-token))) (if (eof-object? (peek-char)) ; check if at end of input (reverse (cons tok tokens)) (loop (cons tok tokens))))))   (define (lexer filename) (with-input-from-file filename (lambda () (read-tokens))))   ;; output tokens to stdout, tab separated ;; line number, column number, token type, optional value (define (display-tokens tokens) (for-each (lambda (token) (display (list-ref token 0)) (display #\tab) (display (list-ref token 1)) (display #\tab) (display (list-ref token 2)) (when (= 4 (length token)) (display #\tab) (display (list-ref token 3))) (newline)) tokens))   ;; read from filename passed on command line (if (= 2 (length (command-line))) (display-tokens (lexer (cadr (command-line)))) (display "Error: provide program filename\n"))  
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"
#Phix
Phix
with javascript_semantics constant cmd = command_line() ?cmd if cmd[1]=cmd[2] then printf(1,"Compiled executable name: %s\n",{cmd[1]}) else printf(1,"Interpreted (using %s) source name: %s\n",cmd[1..2]) end if if length(cmd)>2 then puts(1,"Command line arguments:\n") for i = 3 to length(cmd) do printf(1,"#%d : %s\n",{i,cmd[i]}) end for end if
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"
#PHP
PHP
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);  
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.)
#Fancy
Fancy
# Comments starts with "#" # and last until the end of the line  
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.)
#Fermat
Fermat
Function Foo(n) = {Comments within a function are enclosed within curly brackets.} {You can make multi-line comments such as this one.} n:=n^2 + 3n - 222; {Comments can go after a semicolon.} n:=n+1; n.   ; comments between functions are preceded by semicolons, like this   Function Bar(n) = 2n-1.
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}}, startconfiguration, steps];
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.
#Ela
Ela
if x < 0 then 0 else x
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
#Tailspin
Tailspin
  // matcher testing if the array contains anything not equal to the first element templates allEqual when <[](..1)> do 1 ! when <[<~=$(1)>]> do 0 ! otherwise 1 ! end allEqual   templates strictAscending def a: $; 1 -> # when <$a::length..> do 1 ! when <?($a($) <..~$a($+1)>)> do $ + 1 -> # otherwise 0 ! end strictAscending   // Of course we could just use the same kind of loop for equality templates strictEqual def a: $; 1 -> # when <$a::length..> do 1 ! when <?($a($) <=$a($+1)>)> do $ + 1 -> # otherwise 0 ! end strictEqual  
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
#Tcl
Tcl
tcl::mathop::eq {*}$strings; # All values string-equal tcl::mathop::< {*}$strings; # All values in strict order
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.
#Oberon-2
Oberon-2
  MODULE CommaQuibbling; IMPORT NPCT:Args, Strings, Out;   VAR str: ARRAY 256 OF CHAR;   PROCEDURE Do(VAR s: ARRAY OF CHAR); VAR aux: ARRAY 128 OF CHAR; i,params: LONGINT; BEGIN params := Args.Number() - 1; CASE params OF 0: COPY("{}",s) |1: Args.At(1,aux); Strings.Append("{",s); Strings.Append(aux,s); Strings.Append("}",s); ELSE Strings.Append("{",s); FOR i := 1 TO params - 1 DO Args.At(i,aux); Strings.Append(aux,s); IF i # params - 1 THEN Strings.Append(", ",s) ELSE Strings.Append(" and ", s) END END; Args.At(params,aux); Strings.Append(aux,s); Strings.Append("}",s) END;   END Do;   BEGIN Do(str); Out.String(":> ");Out.String(str);Out.Ln END CommaQuibbling.  
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
#Standard_ML
Standard ML
let rec combs_with_rep k xxs = match k, xxs with | 0, _ -> [[]] | _, [] -> [] | k, x::xs -> List.map (fun ys -> x::ys) (combs_with_rep (k-1) xxs) @ combs_with_rep k xs
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
#Stata
Stata
function combrep(v,k) { n = cols(v) a = J(comb(n+k-1,k),k,v[1]) u = J(1,k,1) for (i=2; 1; i++) { for (j=k; j>0; j--) { if (u[j]<n) break } if (j<1) return(a) m = u[j]+1 for (; j<=k; j++) u[j] = m a[i,.] = v[u] } }   combrep(("iced","jam","plain"),2)   a = combrep(1..10,3) rows(a)
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
#Standard_ML
Standard ML
(*------------------------------------------------------------------*) (* The Rosetta Code lexical analyzer, in Standard ML. Based on the ATS and the OCaml. The intended compiler is Mlton or Poly/ML; there is a tiny difference near the end of the file, depending on which compiler is used. *)   (*------------------------------------------------------------------*) (* The following functions are compatible with ASCII. *)   fun is_digit ichar = 48 <= ichar andalso ichar <= 57   fun is_lower ichar = 97 <= ichar andalso ichar <= 122   fun is_upper ichar = 65 <= ichar andalso ichar <= 90   fun is_alpha ichar = is_lower ichar orelse is_upper ichar   fun is_alnum ichar = is_digit ichar orelse is_alpha ichar   fun is_ident_start ichar = is_alpha ichar orelse ichar = 95   fun is_ident_continuation ichar = is_alnum ichar orelse ichar = 95   fun is_space ichar = ichar = 32 orelse (9 <= ichar andalso ichar <= 13)   (*------------------------------------------------------------------*) (* Character input more like that of C. There are various advantages and disadvantages to this method, but key points in its favor are: (a) it is how character input is done in the original ATS code, (b) Unicode code points are 21-bit positive integers. *)   val eof = ~1   fun input_ichar inpf = case TextIO.input1 inpf of NONE => eof | SOME c => Char.ord c   (*------------------------------------------------------------------*)   (* The type of an input character. *)   structure Ch = struct   type t = { ichar : int, line_no : int, column_no : int }   end   (*------------------------------------------------------------------*) (* Inputting with unlimited pushback, and with counting of lines and columns. *)   structure Inp = struct   type t = { inpf : TextIO.instream, pushback : Ch.t list, line_no : int, column_no : int }   fun of_instream inpf = { inpf = inpf, pushback = [], line_no = 1, column_no = 1 } : t   fun get_ch ({ inpf = inpf, pushback = pushback, line_no = line_no, column_no = column_no } : t) = case pushback of ch :: tail => let val inp = { inpf = inpf, pushback = tail, line_no = line_no, column_no = column_no } in (ch, inp) end | [] => let val ichar = input_ichar inpf val ch = { ichar = ichar, line_no = line_no, column_no = column_no } in if ichar = Char.ord #"\n" then let val inp = { inpf = inpf, pushback = [], line_no = line_no + 1, column_no = 1 } in (ch, inp) end else let val inp = { inpf = inpf, pushback = [], line_no = line_no, column_no = column_no + 1 } in (ch, inp) end end   fun push_back_ch (ch, inp : t) = { inpf = #inpf inp, pushback = ch :: #pushback inp, line_no = #line_no inp, column_no = #column_no inp }   end   (*------------------------------------------------------------------*) (* Tokens, appearing in tuples with arguments, and with line and column numbers. The tokens are integers, so they can be used as array indices. *)   val token_ELSE = 0 val token_IF = 1 val token_PRINT = 2 val token_PUTC = 3 val token_WHILE = 4 val token_MULTIPLY = 5 val token_DIVIDE = 6 val token_MOD = 7 val token_ADD = 8 val token_SUBTRACT = 9 val token_NEGATE = 10 val token_LESS = 11 val token_LESSEQUAL = 12 val token_GREATER = 13 val token_GREATEREQUAL = 14 val token_EQUAL = 15 val token_NOTEQUAL = 16 val token_NOT = 17 val token_ASSIGN = 18 val token_AND = 19 val token_OR = 20 val token_LEFTPAREN = 21 val token_RIGHTPAREN = 22 val token_LEFTBRACE = 23 val token_RIGHTBRACE = 24 val token_SEMICOLON = 25 val token_COMMA = 26 val token_IDENTIFIER = 27 val token_INTEGER = 28 val token_STRING = 29 val token_END_OF_INPUT = 30   (* A *very* simple perfect hash for the reserved words. (Yes, this is overkill, except for demonstration of the principle.) *)   val reserved_words = Vector.fromList ["if", "print", "else", "", "putc", "", "", "while", ""] val reserved_word_tokens = Vector.fromList [token_IF, token_PRINT, token_ELSE, token_IDENTIFIER, token_PUTC, token_IDENTIFIER, token_IDENTIFIER, token_WHILE, token_IDENTIFIER]   fun reserved_word_lookup (s, line_no, column_no) = if (String.size s) < 2 then (token_IDENTIFIER, s, line_no, column_no) else let val hashval = (Char.ord (String.sub (s, 0)) + Char.ord (String.sub (s, 1))) mod 9 val token = Vector.sub (reserved_word_tokens, hashval) in if token = token_IDENTIFIER orelse s <> Vector.sub (reserved_words, hashval) then (token_IDENTIFIER, s, line_no, column_no) else (token, s, line_no, column_no) end   (* Token to string lookup. *)   val token_names = Vector.fromList ["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"]   fun token_name token = Vector.sub (token_names, token)   (*------------------------------------------------------------------*)   exception Unterminated_comment of int * int exception Unterminated_character_literal of int * int exception Multicharacter_literal of int * int exception End_of_input_in_string_literal of int * int exception End_of_line_in_string_literal of int * int exception Unsupported_escape of int * int * char exception Invalid_integer_literal of int * int * string exception Unexpected_character of int * int * char   (*------------------------------------------------------------------*) (* Skipping past spaces and comments. (In the Rosetta Code tiny language, a comment, if you think about it, is a kind of space.) *)   fun scan_comment (inp, line_no, column_no) = let fun loop inp = let val (ch, inp) = Inp.get_ch inp in if #ichar ch = eof then raise Unterminated_comment (line_no, column_no) else if #ichar ch = Char.ord #"*" then let val (ch1, inp) = Inp.get_ch inp in if #ichar ch1 = eof then raise Unterminated_comment (line_no, column_no) else if #ichar ch1 = Char.ord #"/" then inp else loop inp end else loop inp end in loop inp end   fun skip_spaces_and_comments inp = let fun loop inp = let val (ch, inp) = Inp.get_ch inp in if is_space (#ichar ch) then loop inp else if #ichar ch = Char.ord #"/" then let val (ch1, inp) = Inp.get_ch inp in if #ichar ch1 = Char.ord #"*" then loop (scan_comment (inp, #line_no ch, #column_no ch)) else let val inp = Inp.push_back_ch (ch1, inp) val inp = Inp.push_back_ch (ch, inp) in inp end end else Inp.push_back_ch (ch, inp) end in loop inp end   (*------------------------------------------------------------------*) (* Integer literals, identifiers, and reserved words. *)   fun scan_word (lst, inp) = let val (ch, inp) = Inp.get_ch inp in if is_ident_continuation (#ichar ch) then scan_word (Char.chr (#ichar ch) :: lst, inp) else (lst, Inp.push_back_ch (ch, inp)) end   fun scan_integer_literal inp = let val (ch, inp) = Inp.get_ch inp val (lst, inp) = scan_word ([Char.chr (#ichar ch)], inp) val s = String.implode (List.rev lst) in if List.all (fn c => is_digit (Char.ord c)) lst then ((token_INTEGER, s, #line_no ch, #column_no ch), inp) else raise Invalid_integer_literal (#line_no ch, #column_no ch, s) end   fun scan_identifier_or_reserved_word inp = let val (ch, inp) = Inp.get_ch inp val (lst, inp) = scan_word ([Char.chr (#ichar ch)], inp) val s = String.implode (List.rev lst) val toktup = reserved_word_lookup (s, #line_no ch, #column_no ch) in (toktup, inp) end   (*------------------------------------------------------------------*) (* String literals. *)   fun scan_string_literal inp = let val (ch, inp) = Inp.get_ch inp   fun scan (lst, inp) = let val (ch1, inp) = Inp.get_ch inp in if #ichar ch1 = eof then raise End_of_input_in_string_literal (#line_no ch, #column_no ch) else if #ichar ch1 = Char.ord #"\n" then raise End_of_line_in_string_literal (#line_no ch, #column_no ch) else if #ichar ch1 = Char.ord #"\"" then (lst, inp) else if #ichar ch1 <> Char.ord #"\\" then scan (Char.chr (#ichar ch1) :: lst, inp) else let val (ch2, inp) = Inp.get_ch inp in if #ichar ch2 = Char.ord #"n" then scan (#"n" :: #"\\" :: lst, inp) else if #ichar ch2 = Char.ord #"\\" then scan (#"\\" :: #"\\" :: lst, inp) else if #ichar ch2 = eof then raise End_of_input_in_string_literal (#line_no ch, #column_no ch) else if #ichar ch2 = Char.ord #"\n" then raise End_of_line_in_string_literal (#line_no ch, #column_no ch) else raise Unsupported_escape (#line_no ch1, #column_no ch1, Char.chr (#ichar ch2)) end end   val lst = #"\"" :: [] val (lst, inp) = scan (lst, inp) val lst = #"\"" :: lst val s = String.implode (List.rev lst) in ((token_STRING, s, #line_no ch, #column_no ch), inp) end   (*------------------------------------------------------------------*) (* Character literals. *)   fun scan_character_literal_without_checking_end inp = let val (ch, inp) = Inp.get_ch inp val (ch1, inp) = Inp.get_ch inp in if #ichar ch1 = eof then raise Unterminated_character_literal (#line_no ch, #column_no ch) else if #ichar ch1 = Char.ord #"\\" then let val (ch2, inp) = Inp.get_ch inp in if #ichar ch2 = eof then raise Unterminated_character_literal (#line_no ch, #column_no ch) else if #ichar ch2 = Char.ord #"n" then let val s = Int.toString (Char.ord #"\n") in ((token_INTEGER, s, #line_no ch, #column_no ch), inp) end else if #ichar ch2 = Char.ord #"\\" then let val s = Int.toString (Char.ord #"\\") in ((token_INTEGER, s, #line_no ch, #column_no ch), inp) end else raise Unsupported_escape (#line_no ch1, #column_no ch1, Char.chr (#ichar ch2)) end else let val s = Int.toString (#ichar ch1) in ((token_INTEGER, s, #line_no ch, #column_no ch), inp) end end   fun scan_character_literal inp = let val (toktup, inp) = scan_character_literal_without_checking_end inp val (_, _, line_no, column_no) = toktup   fun check_end inp = let val (ch, inp) = Inp.get_ch inp in if #ichar ch = Char.ord #"'" then inp else let fun loop_to_end (ch1 : Ch.t, inp) = if #ichar ch1 = eof then raise Unterminated_character_literal (line_no, column_no) else if #ichar ch1 = Char.ord #"'" then raise Multicharacter_literal (line_no, column_no) else let val (ch1, inp) = Inp.get_ch inp in loop_to_end (ch1, inp) end in loop_to_end (ch, inp) end end   val inp = check_end inp in (toktup, inp) end   (*------------------------------------------------------------------*)   fun get_next_token inp = let val inp = skip_spaces_and_comments inp val (ch, inp) = Inp.get_ch inp val ln = #line_no ch val cn = #column_no ch in if #ichar ch = eof then ((token_END_OF_INPUT, "", ln, cn), inp) else case Char.chr (#ichar ch) of #"," => ((token_COMMA, ",", ln, cn), inp) | #";" => ((token_SEMICOLON, ";", ln, cn), inp) | #"(" => ((token_LEFTPAREN, "(", ln, cn), inp) | #")" => ((token_RIGHTPAREN, ")", ln, cn), inp) | #"{" => ((token_LEFTBRACE, "{", ln, cn), inp) | #"}" => ((token_RIGHTBRACE, "}", ln, cn), inp) | #"*" => ((token_MULTIPLY, "*", ln, cn), inp) | #"/" => ((token_DIVIDE, "/", ln, cn), inp) | #"%" => ((token_MOD, "%", ln, cn), inp) | #"+" => ((token_ADD, "+", ln, cn), inp) | #"-" => ((token_SUBTRACT, "-", ln, cn), inp) | #"<" => let val (ch1, inp) = Inp.get_ch inp in if #ichar ch1 = Char.ord #"=" then ((token_LESSEQUAL, "<=", ln, cn), inp) else let val inp = Inp.push_back_ch (ch1, inp) in ((token_LESS, "<", ln, cn), inp) end end | #">" => let val (ch1, inp) = Inp.get_ch inp in if #ichar ch1 = Char.ord #"=" then ((token_GREATEREQUAL, ">=", ln, cn), inp) else let val inp = Inp.push_back_ch (ch1, inp) in ((token_GREATER, ">", ln, cn), inp) end end | #"=" => let val (ch1, inp) = Inp.get_ch inp in if #ichar ch1 = Char.ord #"=" then ((token_EQUAL, "==", ln, cn), inp) else let val inp = Inp.push_back_ch (ch1, inp) in ((token_ASSIGN, "=", ln, cn), inp) end end | #"!" => let val (ch1, inp) = Inp.get_ch inp in if #ichar ch1 = Char.ord #"=" then ((token_NOTEQUAL, "!=", ln, cn), inp) else let val inp = Inp.push_back_ch (ch1, inp) in ((token_NOT, "!", ln, cn), inp) end end | #"&" => let val (ch1, inp) = Inp.get_ch inp in if #ichar ch1 = Char.ord #"&" then ((token_AND, "&&", ln, cn), inp) else raise Unexpected_character (#line_no ch, #column_no ch, Char.chr (#ichar ch)) end | #"|" => let val (ch1, inp) = Inp.get_ch inp in if #ichar ch1 = Char.ord #"|" then ((token_OR, "||", ln, cn), inp) else raise Unexpected_character (#line_no ch, #column_no ch, Char.chr (#ichar ch)) end | #"\"" => let val inp = Inp.push_back_ch (ch, inp) in scan_string_literal inp end | #"'" => let val inp = Inp.push_back_ch (ch, inp) in scan_character_literal inp end | _ => if is_digit (#ichar ch) then let val inp = Inp.push_back_ch (ch, inp) in scan_integer_literal inp end else if is_ident_start (#ichar ch) then let val inp = Inp.push_back_ch (ch, inp) in scan_identifier_or_reserved_word inp end else raise Unexpected_character (#line_no ch, #column_no ch, Char.chr (#ichar ch)) end   fun output_integer_rightjust (outf, num) = (if num < 10 then TextIO.output (outf, " ") else if num < 100 then TextIO.output (outf, " ") else if num < 1000 then TextIO.output (outf, " ") else if num < 10000 then TextIO.output (outf, " ") else (); TextIO.output (outf, Int.toString num))   fun print_token (outf, toktup) = let val (token, arg, line_no, column_no) = toktup val name = token_name token val (padding, str) = if token = token_IDENTIFIER then (" ", arg) else if token = token_INTEGER then (" ", arg) else if token = token_STRING then (" ", arg) else("", "") in output_integer_rightjust (outf, line_no); TextIO.output (outf, " "); output_integer_rightjust (outf, column_no); TextIO.output (outf, " "); TextIO.output (outf, name); TextIO.output (outf, padding); TextIO.output (outf, str); TextIO.output (outf, "\n") end   fun scan_text (outf, inp) = let fun loop inp = let val (toktup, inp) = get_next_token inp in (print_token (outf, toktup); let val (token, _, _, _) = toktup in if token <> token_END_OF_INPUT then loop inp else () end) end in loop inp end   (*------------------------------------------------------------------*)   fun main () = let val args = CommandLine.arguments () val (inpf_filename, outf_filename) = case args of [] => ("-", "-") | name :: [] => (name, "-") | name1 :: name2 :: _ => (name1, name2) val inpf = if inpf_filename = "-" then TextIO.stdIn else TextIO.openIn inpf_filename handle (IO.Io _) => (TextIO.output (TextIO.stdErr, "Failure opening \""); TextIO.output (TextIO.stdErr, inpf_filename); TextIO.output (TextIO.stdErr, "\" for input\n"); OS.Process.exit OS.Process.failure) val outf = if outf_filename = "-" then TextIO.stdOut else TextIO.openOut outf_filename handle (IO.Io _) => (TextIO.output (TextIO.stdErr, "Failure opening \""); TextIO.output (TextIO.stdErr, outf_filename); TextIO.output (TextIO.stdErr, "\" for output\n"); OS.Process.exit OS.Process.failure) val inp = Inp.of_instream inpf in scan_text (outf, inp) end handle Unterminated_comment (line_no, column_no) => (TextIO.output (TextIO.stdErr, ": unterminated comment "); TextIO.output (TextIO.stdErr, "starting at "); TextIO.output (TextIO.stdErr, Int.toString line_no); TextIO.output (TextIO.stdErr, ":"); TextIO.output (TextIO.stdErr, Int.toString column_no); TextIO.output (TextIO.stdErr, "\n"); OS.Process.exit OS.Process.failure) | Unterminated_character_literal (line_no, column_no) => (TextIO.output (TextIO.stdErr, ": unterminated character "); TextIO.output (TextIO.stdErr, "literal starting at "); TextIO.output (TextIO.stdErr, Int.toString line_no); TextIO.output (TextIO.stdErr, ":"); TextIO.output (TextIO.stdErr, Int.toString column_no); TextIO.output (TextIO.stdErr, "\n"); OS.Process.exit OS.Process.failure) | Multicharacter_literal (line_no, column_no) => (TextIO.output (TextIO.stdErr, ": unsupported multicharacter"); TextIO.output (TextIO.stdErr, " literal starting at "); TextIO.output (TextIO.stdErr, Int.toString line_no); TextIO.output (TextIO.stdErr, ":"); TextIO.output (TextIO.stdErr, Int.toString column_no); TextIO.output (TextIO.stdErr, "\n"); OS.Process.exit OS.Process.failure) | End_of_input_in_string_literal (line_no, column_no) => (TextIO.output (TextIO.stdErr, ": end of input in string"); TextIO.output (TextIO.stdErr, " literal starting at "); TextIO.output (TextIO.stdErr, Int.toString line_no); TextIO.output (TextIO.stdErr, ":"); TextIO.output (TextIO.stdErr, Int.toString column_no); TextIO.output (TextIO.stdErr, "\n"); OS.Process.exit OS.Process.failure) | End_of_line_in_string_literal (line_no, column_no) => (TextIO.output (TextIO.stdErr, ": end of line in string"); TextIO.output (TextIO.stdErr, " literal starting at "); TextIO.output (TextIO.stdErr, Int.toString line_no); TextIO.output (TextIO.stdErr, ":"); TextIO.output (TextIO.stdErr, Int.toString column_no); TextIO.output (TextIO.stdErr, "\n"); OS.Process.exit OS.Process.failure) | Unsupported_escape (line_no, column_no, c) => (TextIO.output (TextIO.stdErr, CommandLine.name ()); TextIO.output (TextIO.stdErr, ": unsupported escape \\"); TextIO.output (TextIO.stdErr, Char.toString c); TextIO.output (TextIO.stdErr, " at "); TextIO.output (TextIO.stdErr, Int.toString line_no); TextIO.output (TextIO.stdErr, ":"); TextIO.output (TextIO.stdErr, Int.toString column_no); TextIO.output (TextIO.stdErr, "\n"); OS.Process.exit OS.Process.failure) | Invalid_integer_literal (line_no, column_no, str) => (TextIO.output (TextIO.stdErr, CommandLine.name ()); TextIO.output (TextIO.stdErr, ": invalid integer literal "); TextIO.output (TextIO.stdErr, str); TextIO.output (TextIO.stdErr, " at "); TextIO.output (TextIO.stdErr, Int.toString line_no); TextIO.output (TextIO.stdErr, ":"); TextIO.output (TextIO.stdErr, Int.toString column_no); TextIO.output (TextIO.stdErr, "\n"); OS.Process.exit OS.Process.failure) | Unexpected_character (line_no, column_no, c) => (TextIO.output (TextIO.stdErr, CommandLine.name ()); TextIO.output (TextIO.stdErr, ": unexpected character '"); TextIO.output (TextIO.stdErr, Char.toString c); TextIO.output (TextIO.stdErr, "' at "); TextIO.output (TextIO.stdErr, Int.toString line_no); TextIO.output (TextIO.stdErr, ":"); TextIO.output (TextIO.stdErr, Int.toString column_no); TextIO.output (TextIO.stdErr, "\n"); OS.Process.exit OS.Process.failure);   (*------------------------------------------------------------------*) (* For the Mlton compiler, include the following. For Poly/ML, comment it out. *) main ();   (*------------------------------------------------------------------*) (* Instructions for GNU Emacs. *)   (* local variables: *) (* mode: sml *) (* sml-indent-level: 2 *) (* sml-indent-args: 2 *) (* end: *) (*------------------------------------------------------------------*)
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"
#Picat
Picat
main(ARGS) => println(ARGS). main(_) => true.
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"
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (de c () (prinl "Got 'c': " (opt)) )   (de h () (prinl "Got 'h': " (opt)) )   (load T) (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"
#PL.2FI
PL/I
  /* The entire command line except the command word itself is passed */ /* to the parameter variable in PL/I. */ program: procedure (command_line) options (main); declare command_line character (100) varying;   ...   end program;  
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.)
#Fish
Fish
v This is the Fish version of the Integer sequence task >0>:n1+v all comments here ^o" "< still here And of course here :)
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.)
#Forth
Forth
\ The backslash skips everything else on the line ( The left paren skips everything up to the next right paren on the same line)
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.
#MATLAB
MATLAB
life
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.
#Erlang
Erlang
case X of {N,M} when N > M -> M; {N,M} when N < M -> N; _ -> equal 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
#VBA
VBA
  Private Function IsEqualOrAscending(myList) As String Dim i&, boolEqual As Boolean, boolAsc As Boolean   On Error Resume Next If UBound(myList) > 0 Then If Err.Number > 0 Then IsEqualOrAscending = "Error " & Err.Number & " : Empty array" On Error GoTo 0 Exit Function Else For i = 1 To UBound(myList) If myList(i) <> myList(i - 1) Then boolEqual = True If myList(i) <= myList(i - 1) Then boolAsc = True Next End If End If IsEqualOrAscending = "List : " & Join(myList, ",") & ", IsEqual : " & (Not boolEqual) & ", IsAscending : " & Not boolAsc End Function  
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
#VBScript
VBScript
  Function string_compare(arr) lexical = "Pass" ascending = "Pass" For i = 0 To UBound(arr) If i+1 <= UBound(arr) Then If arr(i) <> arr(i+1) Then lexical = "Fail" End If If arr(i) >= arr(i+1) Then ascending = "Fail" End If End If Next string_compare = "List: " & Join(arr,",") & vbCrLf &_ "Lexical Test: " & lexical & vbCrLf &_ "Ascending Test: " & ascending & vbCrLf End Function   WScript.StdOut.WriteLine string_compare(Array("AA","BB","CC")) WScript.StdOut.WriteLine string_compare(Array("AA","AA","AA")) WScript.StdOut.WriteLine string_compare(Array("AA","CC","BB")) WScript.StdOut.WriteLine string_compare(Array("AA","ACB","BB","CC")) WScript.StdOut.WriteLine string_compare(Array("FF"))  
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.
#Objeck
Objeck
class Quibbler { function : Quibble(words : String[]) ~ String { text := "{";   each(i : words) { text += words[i]; if(i < words->Size() - 2) { text += ", "; } else if(i = words->Size() - 2) { text += " and "; }; }; text += "}";   return text; }   function : Main(args : String[]) ~ Nil { words := String->New[0]; Quibble(words)->PrintLine();   words := ["ABC"]; Quibble(words)->PrintLine();   words := ["ABC", "DEF"]; Quibble(words)->PrintLine();   words := ["ABC", "DEF", "G", "H"]; Quibble(words)->PrintLine(); } }
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
#Swift
Swift
func combosWithRep<T>(var objects: [T], n: Int) -> [[T]] { if n == 0 { return [[]] } else { var combos = [[T]]() while let element = objects.last { combos.appendContentsOf(combosWithRep(objects, n: n - 1).map{ $0 + [element] }) objects.removeLast() } return combos } } print(combosWithRep(["iced", "jam", "plain"], n: 2).map {$0.joinWithSeparator(" and ")}.joinWithSeparator("\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
#Tcl
Tcl
package require Tcl 8.5 proc combrepl {set n {presorted no}} { if {!$presorted} { set set [lsort $set] } if {[incr n 0] < 1} { return {} } elseif {$n < 2} { return $set } # Recursive call set res [combrepl $set [incr n -1] yes] set result {} foreach item $set { foreach inner $res { dict set result [lsort [list $item {*}$inner]] {} } } return [dict keys $result] }   puts [combrepl {iced jam plain} 2] puts [llength [combrepl {1 2 3 4 5 6 7 8 9 10} 3]]
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
#Wren
Wren
import "/dynamic" for Enum, Struct, Tuple import "/str" for Char import "/fmt" for Fmt import "/ioutil" for FileUtil import "os" for Process   var tokens = [ "EOI", "Mul", "Div", "Mod", "Add", "Sub", "Negate", "Not", "Lss", "Leq", "Gtr", "Geq", "Eq", "Neq", "Assign", "And", "Or", "If", "Else", "While", "Print", "Putc", "Lparen", "Rparen", "Lbrace", "Rbrace", "Semi", "Comma", "Ident", "Integer", "String" ]   var Token = Enum.create("Token", tokens)   var TokData = Struct.create("TokData", ["eline", "ecol", "tok", "v"])   var Symbol = Tuple.create("Symbol", ["name", "tok"])   // symbol table var symtab = []   var curLine = "" var curCh = "" var lineNum = 0 var colNum = 0 var etx = 4 // used to signify EOI   var lines = [] var lineCount = 0   var errorMsg = Fn.new { |eline, ecol, msg| Fiber.abort("(%(eline):%(ecol)) %(msg)") }   // add an identifier to the symbpl table var install = Fn.new { |name, tok| var sym = Symbol.new(name, tok) symtab.add(sym) }   // search for an identifier in the symbol table var lookup = Fn.new { |name| for (i in 0...symtab.count) { if (symtab[i].name == name) return i } return -1 }   // read the next line of input from the source file var nextLine // recursive function nextLine = Fn.new { if (lineNum == lineCount) { curCh = etx curLine = "" colNum = 1 return } curLine = lines[lineNum] lineNum = lineNum + 1 colNum = 0 if (curLine == "") nextLine.call() // skip blank lines }   // get the next char var nextChar = Fn.new { if (colNum >= curLine.count) nextLine.call() if (colNum < curLine.count) { curCh = curLine[colNum] colNum = colNum + 1 } }   var follow = Fn.new { |eline, ecol, expect, ifyes, ifno| if (curCh == expect) { nextChar.call() return ifyes } if (ifno == Token.EOI) { errorMsg.call(eline, ecol, "follow unrecognized character: " + curCh) } return ifno }   var getTok // recursive function getTok = Fn.new { // skip whitespace while (curCh == " " || curCh == "\t" || curCh == "\n") nextChar.call() var td = TokData.new(lineNum, colNum, 0, "") if (curCh == etx) { td.tok = Token.EOI return td } if (curCh == "{") { td.tok = Token.Lbrace nextChar.call() return td } if (curCh == "}") { td.tok = Token.Rbrace nextChar.call() return td } if (curCh == "(") { td.tok = Token.Lparen nextChar.call() return td } if (curCh == ")") { td.tok = Token.Rparen nextChar.call() return td } if (curCh == "+") { td.tok = Token.Add nextChar.call() return td } if (curCh == "-") { td.tok = Token.Sub nextChar.call() return td } if (curCh == "*") { td.tok = Token.Mul nextChar.call() return td } if (curCh == "\%") { td.tok = Token.Mod nextChar.call() return td } if (curCh == ";") { td.tok = Token.Semi nextChar.call() return td } if (curCh == ",") { td.tok = Token.Comma nextChar.call() return td } if (curCh == "'") { // single char literals nextChar.call() td.v = curCh.bytes[0].toString if (curCh == "'") { errorMsg.call(td.eline, td.ecol, "Empty character constant") } if (curCh == "\\") { nextChar.call() if (curCh == "n") { td.v = "10" } else if (curCh == "\\") { td.v = "92" } else { errorMsg.call(td.eline, td.ecol, "unknown escape sequence: "+ curCh) } } nextChar.call() if (curCh != "'") { errorMsg.call(td.eline, td.ecol, "multi-character constant") } nextChar.call() td.tok = Token.Integer return td } if (curCh == "<") { nextChar.call() td.tok = follow.call(td.eline, td.ecol, "=", Token.Leq, Token.Lss) return td } if (curCh == ">") { nextChar.call() td.tok = follow.call(td.eline, td.ecol, "=", Token.Geq, Token.Gtr) return td } if (curCh == "!") { nextChar.call() td.tok = follow.call(td.eline, td.ecol, "=", Token.Neq, Token.Not) return td } if (curCh == "=") { nextChar.call() td.tok = follow.call(td.eline, td.ecol, "=", Token.Eq, Token.Assign) return td } if (curCh == "&") { nextChar.call() td.tok = follow.call(td.eline, td.ecol, "&", Token.And, Token.EOI) return td } if (curCh == "|") { nextChar.call() td.tok = follow.call(td.eline, td.ecol, "|", Token.Or, Token.EOI) return td } if (curCh == "\"") { // string td.v = curCh nextChar.call() while (curCh != "\"") { if (curCh == "\n") { errorMsg.call(td.eline, td.ecol, "EOL in string") } if (curCh == etx) { errorMsg.call(td.eline, td.ecol, "EOF in string") } td.v = td.v + curCh nextChar.call() } td.v = td.v + curCh nextChar.call() td.tok = Token.String return td } if (curCh == "/") { // div or comment nextChar.call() if (curCh != "*") { td.tok = Token.Div return td } // skip comments nextChar.call() while (true) { if (curCh == "*") { nextChar.call() if (curCh == "/") { nextChar.call() return getTok.call() } } else if (curCh == etx) { errorMsg.call(td.eline, td.ecol, "EOF in comment") } else { nextChar.call() } } } //integers or identifiers var isNumber = Char.isDigit(curCh) td.v = "" while (Char.isAsciiAlphaNum(curCh) || curCh == "_") { if (!Char.isDigit(curCh)) isNumber = false td.v = td.v + curCh nextChar.call() } if (td.v.count == 0) { errorMsg.call(td.eline, td.ecol, "unknown character: " + curCh) } if (Char.isDigit(td.v[0])) { if (!isNumber) { errorMsg.call(td.eline, td.ecol, "invalid number: " + curCh) } td.tok = Token.Integer return td } var index = lookup.call(td.v) td.tok = (index == -1) ? Token.Ident : symtab[index].tok return td }   var initLex = Fn.new { install.call("else", Token.Else) install.call("if", Token.If) install.call("print", Token.Print) install.call("putc", Token.Putc) install.call("while", Token.While) nextChar.call() }   var process = Fn.new { var tokMap = {} tokMap[Token.EOI] = "End_of_input" tokMap[Token.Mul] = "Op_multiply" tokMap[Token.Div] = "Op_divide" tokMap[Token.Mod] = "Op_mod" tokMap[Token.Add] = "Op_add" tokMap[Token.Sub] = "Op_subtract" tokMap[Token.Negate] = "Op_negate" tokMap[Token.Not] = "Op_not" tokMap[Token.Lss] = "Op_less" tokMap[Token.Leq] = "Op_lessequal" tokMap[Token.Gtr] = "Op_greater" tokMap[Token.Geq] = "Op_greaterequal" tokMap[Token.Eq] = "Op_equal" tokMap[Token.Neq] = "Op_notequal" tokMap[Token.Assign] = "Op_assign" tokMap[Token.And] = "Op_and" tokMap[Token.Or] = "Op_or" tokMap[Token.If] = "Keyword_if" tokMap[Token.Else] = "Keyword_else" tokMap[Token.While] = "Keyword_while" tokMap[Token.Print] = "Keyword_print" tokMap[Token.Putc] = "Keyword_putc" tokMap[Token.Lparen] = "LeftParen" tokMap[Token.Rparen] = "RightParen" tokMap[Token.Lbrace] = "LeftBrace" tokMap[Token.Rbrace] = "RightBrace" tokMap[Token.Semi] = "Semicolon" tokMap[Token.Comma] = "Comma" tokMap[Token.Ident] = "Identifier" tokMap[Token.Integer] = "Integer" tokMap[Token.String] = "String"   while (true) { var td = getTok.call() Fmt.write("$5d $5d $-16s", td.eline, td.ecol, tokMap[td.tok]) if (td.tok == Token.Integer || td.tok == Token.Ident || td.tok == Token.String) { System.print(td.v) } else { System.print() } if (td.tok == Token.EOI) return } }   var args = Process.arguments if (args.count == 0) { System.print("Filename required") return }   lines = FileUtil.readLines(args[0]) lineCount = lines.count initLex.call() process.call()
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"
#Pop11
Pop11
lvars arg; for arg in poparglist do printf(arg, '->%s<-\n'); endfor;
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"
#PowerBASIC
PowerBASIC
? "args: '"; COMMAND$; "'"