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"
#Clean
Clean
import ArgEnv   Start = getCommandLine
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"
#Clojure
Clojure
(dorun (map println *command-line-args*))
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"
#CLU
CLU
% This program needs to be merged with PCLU's "useful.lib", % where get_argv lives. % % pclu -merge $CLUHOME/lib/useful.lib -compile cmdline.clu   start_up = proc () po: stream := stream$primary_output()   args: sequence[string] := get_argv()   for arg: string in sequence[string]$elements(args) do stream$putl(po, "arg: " || arg) end end start_up
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.)
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI comment one line */ /* comment line 1 comment line 2 */   mov r0,#0 @ this comment on end of line mov r1,#0 // authorized comment    
http://rosettacode.org/wiki/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.)
#Arturo
Arturo
; This is a simple single-line comment   a: 10 ; another single-line comment   ; Now, this is a ; multi-line comment
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#Prolog
Prolog
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% %%% The Rosetta Code Virtual Machine, for GNU Prolog. %%% %%% The following code uses GNU Prolog's extensions for global %%% variables. %%% %%% Usage: vm [INPUTFILE [OUTPUTFILE]] %%% The notation "-" means to use standard input or standard output. %%% Leaving out an argument is equivalent to specifying "-". %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   make_and_run_machine(Input, Output) :- make_machine(Input), run_machine(Output).   run_machine(Output) :- repeat, next_instruction(Opcode, Arg), (Opcode == ('halt') -> true ; (run_instruction(Output, Opcode, Arg), fail % Backtracks to the 'repeat'. )).   run_instruction(Output, Opcode, Arg) :- ( (Opcode == ('add'), pop_value(Y), pop_value(X), is(Z, X + Y), push_value(Z)) ; (Opcode == ('sub'), pop_value(Y), pop_value(X), is(Z, X - Y), push_value(Z)) ; (Opcode == ('mul'), pop_value(Y), pop_value(X), is(Z, X * Y), push_value(Z)) ; (Opcode == ('div'), pop_value(Y), pop_value(X), is(Z, X // Y), push_value(Z)) ; (Opcode == ('mod'), pop_value(Y), pop_value(X), is(Z, X rem Y), push_value(Z)) ; (Opcode == ('lt'), pop_value(Y), pop_value(X), (X < Y -> Z = 1; Z = 0), push_value(Z)) ; (Opcode == ('le'), pop_value(Y), pop_value(X), (X =< Y -> Z = 1; Z = 0), push_value(Z)) ; (Opcode == ('gt'), pop_value(Y), pop_value(X), (X > Y -> Z = 1; Z = 0), push_value(Z)) ; (Opcode == ('ge'), pop_value(Y), pop_value(X), (X >= Y -> Z = 1; Z = 0), push_value(Z)) ; (Opcode == ('eq'), pop_value(Y), pop_value(X), (X =:= Y -> Z = 1; Z = 0), push_value(Z)) ; (Opcode == ('ne'), pop_value(Y), pop_value(X), (X =\= Y -> Z = 1; Z = 0), push_value(Z)) ; (Opcode == ('and'), pop_value(Y), pop_value(X), ((X =\= 0, Y =\= 0) -> Z = 1; Z = 0), push_value(Z)) ; (Opcode == ('or'), pop_value(Y), pop_value(X), ((X =\= 0; Y =\= 0) -> Z = 1; Z = 0), push_value(Z)) ; (Opcode == ('neg'), pop_value(X), is(Z, -X), push_value(Z)) ; (Opcode == ('not'), pop_value(X), (X =:= 0 -> Z = 1; Z = 0), push_value(Z)) ; (Opcode == ('prtc'), pop_value(X), char_code(C, X), write(Output, C)) ; (Opcode == ('prti'), pop_value(X), write(Output, X)) ; (Opcode == ('prts'), pop_value(K), g_read(the_strings(K), S), write(Output, S)) ; (Opcode == ('fetch'), g_read(the_data(Arg), X), push_value(X), skip_argument) ; (Opcode == ('store'), pop_value(X), g_assign(the_data(Arg), X), skip_argument) ; (Opcode == ('push'), push_value(Arg), skip_argument) ; (Opcode == ('jmp'), relative_jump(Arg)) ; (Opcode == ('jz'), pop_value(X), (X =:= 0 -> relative_jump(Arg) ; skip_argument)) ).   relative_jump(Offset) :- g_read(the_program_counter, PC), is(PC1, PC + Offset), g_assign(the_program_counter, PC1).   skip_argument :- g_read(the_program_counter, PC), is(PC1, PC + 4), g_assign(the_program_counter, PC1).   next_instruction(Opcode, Arg) :- g_read(the_program_counter, PC), is(PC1, PC + 1), g_assign(the_program_counter, PC1), g_read(the_code(PC), {Opcode, Arg}).   push_value(X) :- g_read(the_stack_pointer, SP), is(SP1, SP + 1), g_assign(the_stack_pointer, SP1), g_assign(the_stack(SP), X).   pop_value(X) :- g_read(the_stack_pointer, SP), is(SP1, SP - 1), g_assign(the_stack_pointer, SP1), g_read(the_stack(SP1), X).   make_machine(Input) :- get_and_parse_the_header(Input, Datasize, Strings_Count), (Strings_Count =:= 0 -> true ; get_and_parse_the_strings(Input, Strings_Count)), get_and_parse_the_instructions(Input), (Datasize =:= 0 -> true ; g_assign(the_data, g_array(Datasize))), g_assign(the_stack, g_array(2048)), g_assign(the_stack_pointer, 0), g_assign(the_program_counter, 0).   get_and_parse_the_header(Stream, Datasize, Strings_Count) :- get_line(Stream, Line, ('\n')), parse_header(Line, Datasize, Strings_Count).   get_and_parse_the_strings(Stream, Strings_Count) :- % Make 'the_strings' an array of the string literals. get_and_parse_the_strings(Stream, Strings_Count, Lst), g_assign(the_strings, g_array(Lst)). get_and_parse_the_strings(Stream, I, Lst) :- % Note: this implementation is non-tail recursive. (I == 0 -> Lst = [] ; (get_line(Stream, Line, ('\n')), parse_string_literal(Line, S), is(I1, I - 1), get_and_parse_the_strings(Stream, I1, Lst1), Lst = [S | Lst1])).   get_and_parse_the_instructions(Stream) :- get_and_parse_the_instructions(Stream, Lst), keysort(Lst, Lst1), last(Lst1, Addr_Max-_), is(Code_Size, Addr_Max + 5), g_assign(the_code, g_array(Code_Size, {('halt'), 0})), maplist(fill_instruction, Lst1). get_and_parse_the_instructions(Stream, Lst) :- get_and_parse_the_instructions(Stream, [], Lst). get_and_parse_the_instructions(Stream, Lst0, Lst) :- % This implementation is tail recursive. We consider the order of % the resulting list to be arbitrary. (get_line(Stream, Line, Terminal), drop_spaces(Line, S), (S = [] -> (Terminal = end_of_file -> Lst = Lst0 ; get_and_parse_the_instructions(Stream, Lst0, Lst)) ; (parse_instruction(S, Address, Opcode, Arg), Instr = Address-{Opcode, Arg}, (Terminal = end_of_file -> reverse([Instr | Lst0], Lst) ; get_and_parse_the_instructions(Stream, [Instr | Lst0], Lst))))).   fill_instruction(Addr-Instr) :- g_assign(the_code(Addr), Instr).   parse_header(Line, Datasize, Strings_Count) :- drop_nondigits(Line, Lst1), split_digits(Lst1, Datasize_Digits, Rest1), drop_nondigits(Rest1, Lst2), split_digits(Lst2, Strings_Digits, _Rest2), number_chars(Datasize, Datasize_Digits), number_chars(Strings_Count, Strings_Digits).   parse_string_literal(Line, S) :- drop_spaces(Line, Lst1), Lst1 = ['"' | Lst2], rework_escape_sequences(Lst2, Lst3), atom_chars(S, Lst3).   rework_escape_sequences(Lst0, Lst) :- (Lst0 = [('"') | _] -> Lst = [] ; (Lst0 = [('\\'), ('n') | Tail1] -> (rework_escape_sequences(Tail1, Lst1), Lst = [('\n') | Lst1]) ; (Lst0 = [('\\'), ('\\') | Tail1] -> (rework_escape_sequences(Tail1, Lst1), Lst = [('\\') | Lst1]) ; (Lst0 = [C | Tail1], rework_escape_sequences(Tail1, Lst1), Lst = [C | Lst1])))).   parse_instruction(Line, Address, Opcode, Arg) :- drop_spaces(Line, Lst1), split_digits(Lst1, Address_Digits, Rest1), number_chars(Address, Address_Digits), drop_spaces(Rest1, Lst2), split_nonspaces(Lst2, Opcode_Chars, Rest2), atom_chars(Opcode, Opcode_Chars), drop_spaces(Rest2, Lst3), (Lst3 = [] -> Arg = 0 ; (Lst3 = [C | Rest3], (is_digit(C) -> (split_digits(Lst3, Arg_Chars, _), number_chars(Arg, Arg_Chars)) ; (C = ('(') -> (split_before_char((')'), Rest3, Arg_Chars, _), number_chars(Arg, Arg_Chars)) ; (C = ('['), split_before_char((']'), Rest3, Arg_Chars, _), number_chars(Arg, Arg_Chars)))))).   is_space(C) :- (C = (' '); C = ('\t'); C = ('\n'); C = ('\v'); C = ('\f'); C = ('\r')).   is_digit(C) :- (C = ('0'); C = ('1'); C = ('2'); C = ('3'); C = ('4'); C = ('5'); C = ('6'); C = ('7'); C = ('8'); C = ('9')).   drop_spaces([], Lst) :- Lst = []. drop_spaces([C | Tail], Lst) :- (is_space(C) -> drop_spaces(Tail, Lst) ; Lst = [C | Tail]).   drop_nondigits([], Lst) :- Lst = []. drop_nondigits([C | Tail], Lst) :- (is_digit(C) -> Lst = [C | Tail] ; drop_nondigits(Tail, Lst)).   split_nonspaces([], Word, Rest) :- (Word = [], Rest = []). split_nonspaces([C | Tail], Word, Rest) :- (is_space(C) -> (Word = [], Rest = [C | Tail]) ; (split_nonspaces(Tail, Word1, Rest), Word = [C | Word1])).   split_digits([], Digits, Rest) :- (Digits = [], Rest = []). split_digits([C | Tail], Digits, Rest) :- (is_digit(C) -> (split_digits(Tail, Digits1, Rest), Digits = [C | Digits1]) ; (Digits = [], Rest = [C | Tail])).   split_before_char(_, [], Before, After) :- (Before = [], After = []). split_before_char(C, [C1 | Rest], Before, After) :- (C = C1 -> (Before = [], After = [C1 | Rest]) ; (split_before_char(C, Rest, Before1, After), Before = [C1 | Before1])).   get_line(Stream, Line, Terminal) :- % Reads a line of input as a list of characters. The character that % terminates the line is returned separately; it may be either '\n' % or end_of_file. get_line_chars(Stream, [], Line, Terminal).   get_line_chars(Stream, Chars0, Chars, Terminal) :- % Helper predicate for get_line. get_char(Stream, C), ((C = end_of_file; C = ('\n')) -> (reverse(Chars0, Chars), Terminal = C) ; get_line_chars(Stream, [C | Chars0], Chars, Terminal)).   main(Args) :- (Args = [] -> current_input(Input), current_output(Output), make_and_run_machine(Input, Output) ; (Args = [Inp_Name] -> (Inp_Name = ('-') -> main([]) ; (open(Inp_Name, 'read', Input), current_output(Output), make_and_run_machine(Input, Output), close(Input))) ; (Args = [Inp_Name, Out_Name | _], (Inp_Name = ('-') -> (Out_Name = ('-') -> main([]) ; (current_input(Input), open(Out_Name, 'write', Output), make_and_run_machine(Input, Output), close(Output))) ; (Out_Name = ('-') -> main([Inp_Name]) ; (open(Inp_Name, 'read', Input), open(Out_Name, 'write', Output), make_and_run_machine(Input, Output), close(Input), close(Output))))))).   main :- argument_list(Args), main(Args).   :- initialization(main).   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Instructions for GNU Emacs-- %%% local variables: %%% mode: prolog %%% prolog-indent-width: 2 %%% end: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#Python
Python
from __future__ import print_function import sys, struct, shlex, operator   nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \ nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \ nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)   all_syms = { "Identifier"  : nd_Ident, "String"  : nd_String, "Integer"  : nd_Integer, "Sequence"  : nd_Sequence, "If"  : nd_If, "Prtc"  : nd_Prtc, "Prts"  : nd_Prts, "Prti"  : nd_Prti, "While"  : nd_While, "Assign"  : nd_Assign, "Negate"  : nd_Negate, "Not"  : nd_Not, "Multiply"  : nd_Mul, "Divide"  : nd_Div, "Mod"  : nd_Mod, "Add"  : nd_Add, "Subtract"  : nd_Sub, "Less"  : nd_Lss, "LessEqual"  : nd_Leq, "Greater"  : nd_Gtr, "GreaterEqual": nd_Geq, "Equal"  : nd_Eql, "NotEqual"  : nd_Neq, "And"  : nd_And, "Or"  : nd_Or}   FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, \ JMP, JZ, PRTC, PRTS, PRTI, HALT = range(24)   operators = {nd_Lss: LT, nd_Gtr: GT, nd_Leq: LE, nd_Geq: GE, nd_Eql: EQ, nd_Neq: NE, nd_And: AND, nd_Or: OR, nd_Sub: SUB, nd_Add: ADD, nd_Div: DIV, nd_Mul: MUL, nd_Mod: MOD}   unary_operators = {nd_Negate: NEG, nd_Not: NOT}   input_file = None code = bytearray() string_pool = {} globals = {} string_n = 0 globals_n = 0 word_size = 4   #*** show error and exit def error(msg): print("%s" % (msg)) exit(1)   def int_to_bytes(val): return struct.pack("<i", val)   def bytes_to_int(bstr): return struct.unpack("<i", bstr)   class Node: def __init__(self, node_type, left = None, right = None, value = None): self.node_type = node_type self.left = left self.right = right self.value = value   #*** def make_node(oper, left, right = None): return Node(oper, left, right)   #*** def make_leaf(oper, n): return Node(oper, value = n)   #*** def emit_byte(x): code.append(x)   #*** def emit_word(x): s = int_to_bytes(x) for x in s: code.append(x)   def emit_word_at(at, n): code[at:at+word_size] = int_to_bytes(n)   def hole(): t = len(code) emit_word(0) return t   #*** def fetch_var_offset(name): global globals_n   n = globals.get(name, None) if n == None: globals[name] = globals_n n = globals_n globals_n += 1 return n   #*** def fetch_string_offset(the_string): global string_n   n = string_pool.get(the_string, None) if n == None: string_pool[the_string] = string_n n = string_n string_n += 1 return n   #*** def code_gen(x): if x == None: return elif x.node_type == nd_Ident: emit_byte(FETCH) n = fetch_var_offset(x.value) emit_word(n) elif x.node_type == nd_Integer: emit_byte(PUSH) emit_word(x.value) elif x.node_type == nd_String: emit_byte(PUSH) n = fetch_string_offset(x.value) emit_word(n) elif x.node_type == nd_Assign: n = fetch_var_offset(x.left.value) code_gen(x.right) emit_byte(STORE) emit_word(n) elif x.node_type == nd_If: code_gen(x.left) # expr emit_byte(JZ) # if false, jump p1 = hole() # make room for jump dest code_gen(x.right.left) # if true statements if (x.right.right != None): emit_byte(JMP) # jump over else statements p2 = hole() emit_word_at(p1, len(code) - p1) if (x.right.right != None): code_gen(x.right.right) # else statements emit_word_at(p2, len(code) - p2) elif x.node_type == nd_While: p1 = len(code) code_gen(x.left) emit_byte(JZ) p2 = hole() code_gen(x.right) emit_byte(JMP) # jump back to the top emit_word(p1 - len(code)) emit_word_at(p2, len(code) - p2) elif x.node_type == nd_Sequence: code_gen(x.left) code_gen(x.right) elif x.node_type == nd_Prtc: code_gen(x.left) emit_byte(PRTC) elif x.node_type == nd_Prti: code_gen(x.left) emit_byte(PRTI) elif x.node_type == nd_Prts: code_gen(x.left) emit_byte(PRTS) elif x.node_type in operators: code_gen(x.left) code_gen(x.right) emit_byte(operators[x.node_type]) elif x.node_type in unary_operators: code_gen(x.left) emit_byte(unary_operators[x.node_type]) else: error("error in code generator - found %d, expecting operator" % (x.node_type))   #*** def code_finish(): emit_byte(HALT)   #*** def list_code(): print("Datasize: %d Strings: %d" % (len(globals), len(string_pool)))   for k in sorted(string_pool, key=string_pool.get): print(k)   pc = 0 while pc < len(code): print("%4d " % (pc), end='') op = code[pc] pc += 1 if op == FETCH: x = bytes_to_int(code[pc:pc+word_size])[0] print("fetch [%d]" % (x)); pc += word_size elif op == STORE: x = bytes_to_int(code[pc:pc+word_size])[0] print("store [%d]" % (x)); pc += word_size elif op == PUSH: x = bytes_to_int(code[pc:pc+word_size])[0] print("push  %d" % (x)); pc += word_size elif op == ADD: print("add") elif op == SUB: print("sub") elif op == MUL: print("mul") elif op == DIV: print("div") elif op == MOD: print("mod") elif op == LT: print("lt") elif op == GT: print("gt") elif op == LE: print("le") elif op == GE: print("ge") elif op == EQ: print("eq") elif op == NE: print("ne") elif op == AND: print("and") elif op == OR: print("or") elif op == NEG: print("neg") elif op == NOT: print("not") elif op == JMP: x = bytes_to_int(code[pc:pc+word_size])[0] print("jmp (%d) %d" % (x, pc + x)); pc += word_size elif op == JZ: x = bytes_to_int(code[pc:pc+word_size])[0] print("jz (%d) %d" % (x, pc + x)); pc += word_size elif op == PRTC: print("prtc") elif op == PRTI: print("prti") elif op == PRTS: print("prts") elif op == HALT: print("halt") else: error("list_code: Unknown opcode %d", (op));   def load_ast(): line = input_file.readline() line_list = shlex.split(line, False, False)   text = line_list[0] if text == ";": return None node_type = all_syms[text]   if len(line_list) > 1: value = line_list[1] if value.isdigit(): value = int(value) return make_leaf(node_type, value)   left = load_ast() right = load_ast() return make_node(node_type, left, right)   #*** main driver input_file = sys.stdin if len(sys.argv) > 1: try: input_file = open(sys.argv[1], "r", 4096) except IOError as e: error("Can't open %s" % sys.argv[1])   n = load_ast() code_gen(n) code_finish() list_code()
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PHP
PHP
  <?php     function retrieveStrings() { if (isset($_POST['input'])) { $strings = explode("\n", $_POST['input']); } else { $strings = ['abcd', '123456789', 'abcdef', '1234567']; } return $strings; }     function setInput() { echo join("\n", retrieveStrings()); }     function setOutput() { $strings = retrieveStrings();   // Remove empty strings // $strings = array_map('trim', $strings); $strings = array_filter($strings);   if (!empty($strings)) { usort($strings, function ($a, $b) { return strlen($b) - strlen($a); }); $max_len = strlen($strings[0]); $min_len = strlen($strings[count($strings) - 1]); foreach ($strings as $s) { $length = strlen($s); if ($length == $max_len) { $predicate = "is the longest string"; } elseif ($length == $min_len) { $predicate = "is the shortest string"; } else { $predicate = "is neither the longest nor the shortest string"; } echo "$s has length $length and $predicate\n"; } } }   ?>     <!DOCTYPE html> <html lang="en">   <head> <style> div { margin-top: 4ch; margin-bottom: 4ch; }   label { display: block; margin-bottom: 1ch; }   textarea { display: block; }   input { display: block; margin-top: 4ch; margin-bottom: 4ch; } </style> </head>     <body> <main> <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8"> <div> <label for="input">Input: </label> <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea> </label> </div> <input type="submit" value="press to compare strings"> </input> <div> <label for="Output">Output: </label> <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea> </div> </form> </main> </body>   </html>
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a parser module/library/class, it would be great if two versions of the solution are provided: One without the parser module, and one with. Grammar The simple programming language to be analyzed is more or less a (very tiny) subset of C. The formal grammar in Extended Backus-Naur Form (EBNF):   stmt_list = {stmt} ;   stmt = ';' | Identifier '=' expr ';' | 'while' paren_expr stmt | 'if' paren_expr stmt ['else' stmt] | 'print' '(' prt_list ')' ';' | 'putc' paren_expr ';' | '{' stmt_list '}'  ;   paren_expr = '(' expr ')' ;   prt_list = (string | expr) {',' (String | expr)} ;   expr = and_expr {'||' and_expr} ; and_expr = equality_expr {'&&' equality_expr} ; equality_expr = relational_expr [('==' | '!=') relational_expr] ; relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ; addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ; multiplication_expr = primary {('*' | '/' | '%') primary } ; primary = Identifier | Integer | '(' expr ')' | ('+' | '-' | '!') primary  ; The resulting AST should be formulated as a Binary Tree. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast The following table shows the input to lex, lex output, and the AST produced by the parser Input to lex Output from lex, input to parse Output from parse count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Specifications List of node type names Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or In the text below, Null/Empty nodes are represented by ";". Non-terminal (internal) nodes For Operators, the following nodes should be created: Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or For each of the above nodes, the left and right sub-nodes are the operands of the respective operation. In pseudo S-Expression format: (Operator expression expression) Negate, Not For these node types, the left node is the operand, and the right node is null. (Operator expression ;) Sequence - sub-nodes are either statements or Sequences. If - left node is the expression, the right node is If node, with it's left node being the if-true statement part, and the right node being the if-false (else) statement part. (If expression (If statement else-statement)) If there is not an else, the tree becomes: (If expression (If statement ;)) Prtc (Prtc (expression) ;) Prts (Prts (String "the string") ;) Prti (Prti (Integer 12345) ;) While - left node is the expression, the right node is the statement. (While expression statement) Assign - left node is the left-hand side of the assignment, the right node is the right-hand side of the assignment. (Assign Identifier expression) Terminal (leaf) nodes: Identifier: (Identifier ident_name) Integer: (Integer 12345) String: (String "Hello World!") ";": Empty node Some simple examples Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path. This simple program: a=11; Produces the following AST, encoded as a binary tree: Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node: (1) Sequence (2) |-- ; (3) |-- Assign (4) |-- Identifier: a (5) |-- Integer: 11 In flattened form: (1) Sequence (2) ; (3) Assign (4) Identifier a (5) Integer 11 This program: a=11; b=22; c=33; Produces the following AST: ( 1) Sequence ( 2) |-- Sequence ( 3) | |-- Sequence ( 4) | | |-- ; ( 5) | | |-- Assign ( 6) | | |-- Identifier: a ( 7) | | |-- Integer: 11 ( 8) | |-- Assign ( 9) | |-- Identifier: b (10) | |-- Integer: 22 (11) |-- Assign (12) |-- Identifier: c (13) |-- Integer: 33 In flattened form: ( 1) Sequence ( 2) Sequence ( 3) Sequence ( 4) ; ( 5) Assign ( 6) Identifier a ( 7) Integer 11 ( 8) Assign ( 9) Identifier b (10) Integer 22 (11) Assign (12) Identifier c (13) Integer 33 Pseudo-code for the parser. Uses Precedence Climbing for expression parsing, and Recursive Descent for statement parsing. The AST is also built: def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error()   while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q))   return x   def paren_expr() expect("(") x = expr(0) expect(")") return x   def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0))   t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t   def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t Once the AST is built, it should be output in a flattened format. This can be as simple as the following def prt_ast(t) if t == NULL print(";\n") else print(t.node_type) if t.node_type in [Identifier, Integer, String] # leaf node print the value of the Ident, Integer or String, "\n" else print("\n") prt_ast(t.left) prt_ast(t.right) If the AST is correctly built, loading it into a subsequent program should be as simple as def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) Finally, the AST can also be tested by running it against one of the AST Interpreter solutions. Test program, assuming this is in a file called prime.t lex <prime.t | parse Input to lex Output from lex, input to parse Output from parse /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 4 1 Identifier count 4 7 Op_assign 4 9 Integer 1 4 10 Semicolon 5 1 Identifier n 5 3 Op_assign 5 5 Integer 1 5 6 Semicolon 6 1 Identifier limit 6 7 Op_assign 6 9 Integer 100 6 12 Semicolon 7 1 Keyword_while 7 7 LeftParen 7 8 Identifier n 7 10 Op_less 7 12 Identifier limit 7 17 RightParen 7 19 LeftBrace 8 5 Identifier k 8 6 Op_assign 8 7 Integer 3 8 8 Semicolon 9 5 Identifier p 9 6 Op_assign 9 7 Integer 1 9 8 Semicolon 10 5 Identifier n 10 6 Op_assign 10 7 Identifier n 10 8 Op_add 10 9 Integer 2 10 10 Semicolon 11 5 Keyword_while 11 11 LeftParen 11 12 LeftParen 11 13 Identifier k 11 14 Op_multiply 11 15 Identifier k 11 16 Op_lessequal 11 18 Identifier n 11 19 RightParen 11 21 Op_and 11 24 LeftParen 11 25 Identifier p 11 26 RightParen 11 27 RightParen 11 29 LeftBrace 12 9 Identifier p 12 10 Op_assign 12 11 Identifier n 12 12 Op_divide 12 13 Identifier k 12 14 Op_multiply 12 15 Identifier k 12 16 Op_notequal 12 18 Identifier n 12 19 Semicolon 13 9 Identifier k 13 10 Op_assign 13 11 Identifier k 13 12 Op_add 13 13 Integer 2 13 14 Semicolon 14 5 RightBrace 15 5 Keyword_if 15 8 LeftParen 15 9 Identifier p 15 10 RightParen 15 12 LeftBrace 16 9 Keyword_print 16 14 LeftParen 16 15 Identifier n 16 16 Comma 16 18 String " is prime\n" 16 31 RightParen 16 32 Semicolon 17 9 Identifier count 17 15 Op_assign 17 17 Identifier count 17 23 Op_add 17 25 Integer 1 17 26 Semicolon 18 5 RightBrace 19 1 RightBrace 20 1 Keyword_print 20 6 LeftParen 20 7 String "Total primes found: " 20 29 Comma 20 31 Identifier count 20 36 Comma 20 38 String "\n" 20 42 RightParen 20 43 Semicolon 21 1 End_of_input Sequence Sequence Sequence Sequence Sequence ; Assign Identifier count Integer 1 Assign Identifier n Integer 1 Assign Identifier limit Integer 100 While Less Identifier n Identifier limit Sequence Sequence Sequence Sequence Sequence ; Assign Identifier k Integer 3 Assign Identifier p Integer 1 Assign Identifier n Add Identifier n Integer 2 While And LessEqual Multiply Identifier k Identifier k Identifier n Identifier p Sequence Sequence ; Assign Identifier p NotEqual Multiply Divide Identifier n Identifier k Identifier k Identifier n Assign Identifier k Add Identifier k Integer 2 If Identifier p If Sequence Sequence ; Sequence Sequence ; Prti Identifier n ; Prts String " is prime\n" ; Assign Identifier count Add Identifier count Integer 1 ; Sequence Sequence Sequence ; Prts String "Total primes found: " ; Prti Identifier count ; Prts String "\n" ; Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#Wren
Wren
import "/dynamic" for Enum, Struct, Tuple import "/fmt" for Fmt import "/ioutil" for FileUtil   var tokens = [ "EOI", "Mul", "Div", "Mod", "Add", "Sub", "Negate", "Not", "Lss", "Leq", "Gtr", "Geq", "Eql", "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 nodes = [ "Ident", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Mul", "Div", "Mod", "Add", "Sub", "Lss", "Leq", "Gtr", "Geq", "Eql", "Neq", "And", "Or" ]   var Node = Enum.create("Node", nodes)   // 'text' field represents ident ot string literal or integer value var TokS = Struct.create("TokS", ["tok", "errLn", "errCol", "text"])   var Tree = Struct.create("Tree", ["nodeType", "left", "right", "value"])   // dependency: Ordered by tok, must remain in same order as Token enum constants var Atr = Tuple.create("Atr", ["text", "enumText", "tok", "rightAssociative", "isBinary", "isUnary", "precedence", "nodeType"])   var atrs = [ Atr.new("EOI", "End_of_input", Token.EOI, false, false, false, -1, -1), Atr.new("*", "Op_multiply", Token.Mul, false, true, false, 13, Node.Mul), Atr.new("/", "Op_divide", Token.Div, false, true, false, 13, Node.Div), Atr.new("\%", "Op_mod", Token.Mod, false, true, false, 13, Node.Mod), Atr.new("+", "Op_add", Token.Add, false, true, false, 12, Node.Add), Atr.new("-", "Op_subtract", Token.Sub, false, true, false, 12, Node.Sub), Atr.new("-", "Op_negate", Token.Negate, false, false, true, 14, Node.Negate), Atr.new("!", "Op_not", Token.Not, false, false, true, 14, Node.Not), Atr.new("<", "Op_less", Token.Lss, false, true, false, 10, Node.Lss), Atr.new("<=", "Op_lessequal", Token.Leq, false, true, false, 10, Node.Leq), Atr.new(">", "Op_greater", Token.Gtr, false, true, false, 10, Node.Gtr), Atr.new(">=", "Op_greaterequal", Token.Geq, false, true, false, 10, Node.Geq), Atr.new("==", "Op_equal", Token.Eql, false, true, false, 9, Node.Eql), Atr.new("!=", "Op_notequal", Token.Neq, false, true, false, 9, Node.Neq), Atr.new("=", "Op_assign", Token.Assign, false, false, false, -1, Node.Assign), Atr.new("&&", "Op_and", Token.And, false, true, false, 5, Node.And), Atr.new("||", "Op_or", Token.Or, false, true, false, 4, Node.Or), Atr.new("if", "Keyword_if", Token.If, false, false, false, -1, Node.If), Atr.new("else", "Keyword_else", Token.Else, false, false, false, -1, -1), Atr.new("while", "Keyword_while", Token.While, false, false, false, -1, Node.While), Atr.new("print", "Keyword_print", Token.Print, false, false, false, -1, -1), Atr.new("putc", "Keyword_putc", Token.Putc, false, false, false, -1, -1), Atr.new("(", "LeftParen", Token.Lparen, false, false, false, -1, -1), Atr.new(")", "RightParen", Token.Rparen, false, false, false, -1, -1), Atr.new("{", "LeftBrace", Token.Lbrace, false, false, false, -1, -1), Atr.new("}", "RightBrace", Token.Rbrace, false, false, false, -1, -1), Atr.new(";", "Semicolon", Token.Semi, false, false, false, -1, -1), Atr.new(",", "Comma", Token.Comma, false, false, false, -1, -1), Atr.new("Ident", "Identifier", Token.Ident, false, false, false, -1, Node.Ident), Atr.new("Integer literal", "Integer", Token.Integer, false, false, false, -1, Node.Integer), Atr.new("String literal", "String", Token.String, false, false, false, -1, Node.String), ]   var displayNodes = [ "Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add", "Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal", "NotEqual", "And", "Or" ]   var token = TokS.new(0, 0, 0, "")   var reportError = Fn.new { |eline, ecol, msg| Fiber.abort("(%(eline):%(ecol)) error : %(msg)") }   // return internal version of name var getEnum = Fn.new { |name| for (atr in atrs) { if (atr.enumText == name) return atr.tok } reportError.call(0, 0, "Unknown token %(name)") }   var lines = [] var lineCount = 0 var lineNum = 0   var getTok = Fn.new { var tok = TokS.new(0, 0, 0, "") if (lineNum < lineCount) { var line = lines[lineNum].trimEnd(" \t") lineNum = lineNum + 1 var fields = line.split(" ").where { |s| s != "" }.toList // [ ]*{lineno}[ ]+{colno}[ ]+token[ ]+optional tok.errLn = Num.fromString(fields[0]) tok.errCol = Num.fromString(fields[1]) tok.tok = getEnum.call(fields[2]) var le = fields.count if (le == 4) { tok.text = fields[3] } else if (le > 4) { var idx = line.indexOf("\"") tok.text = line[idx..-1] } } return tok }   var makeNode = Fn.new { |nodeType, left, right| Tree.new(nodeType, left, right, "") }   var makeLeaf = Fn.new { |nodeType, value| Tree.new(nodeType, null, null, value) }   var expect = Fn.new { |msg, s| if (token.tok == s) { token = getTok.call() return } reportError.call(token.errLn, token.errCol, Fmt.swrite("$s: Expecting '$s', found '$s'", msg, atrs[s].text, atrs[token.tok].text)) }   var parenExpr // forward reference   var expr // recursive function expr = Fn.new { |p| var x var node var t = token.tok if (t == Token.Lparen) { x = parenExpr.call() } else if (t == Token.Sub || t == Token.Add) { var op = t token = getTok.call() node = expr.call(atrs[Token.Negate].precedence) if (op == Token.Sub) { x = makeNode.call(Node.negate, node, null) } else { x = node } } else if (t == Token.Not) { token = getTok.call() x = makeNode.call(Node.Not, expr.call(atrs[Token.Not].precedence), null) } else if (t == Token.Ident) { x = makeLeaf.call(Node.Ident, token.text) token = getTok.call() } else if (t == Token.Integer) { x = makeLeaf.call(Node.Integer, token.text) token = getTok.call() } else { reportError.call(token.errLn, token.errCol, Fmt.swrite("Expecting a primary, found: $s", atrs[token.tok].text)) }   while (atrs[token.tok].isBinary && atrs[token.tok].precedence >= p) { var op = token.tok token = getTok.call() var q = atrs[op].precedence if (!atrs[op].rightAssociative) q = q + 1 node = expr.call(q) x = makeNode.call(atrs[op].nodeType, x, node) } return x }   parenExpr = Fn.new { expect.call("parenExpr", Token.Lparen) var t = expr.call(0) expect.call("parenExpr", Token.Rparen) return t }   var stmt // recursive function stmt = Fn.new { var t var v var e var s var s2 var tt = token.tok if (tt == Token.If) { token = getTok.call() e = parenExpr.call() s = stmt.call() s2 = null if (token.tok == Token.Else) { token = getTok.call() s2 = stmt.call() } t = makeNode.call(Node.If, e, makeNode.call(Node.If, s, s2)) } else if (tt == Token.Putc) { token = getTok.call() e = parenExpr.call() t = makeNode.call(Node.Prtc, e, null) expect.call("Putc", Token.Semi) } else if (tt == Token.Print) { // print '(' expr {',' expr} ')' token = getTok.call() expect.call("Print", Token.Lparen) while (true) { if (token.tok == Token.String) { e = makeNode.call(Node.Prts, makeLeaf.call(Node.String, token.text), null) token = getTok.call() } else { e = makeNode.call(Node.Prti, expr.call(0), null) } t = makeNode.call(Node.Sequence, t, e) if (token.tok != Token.Comma) break expect.call("Print", Token.Comma) } expect.call("Print", Token.Rparen) expect.call("Print", Token.Semi) } else if (tt == Token.Semi) { token = getTok.call() } else if (tt == Token.Ident) { v = makeLeaf.call(Node.Ident, token.text) token = getTok.call() expect.call("assign", Token.Assign) e = expr.call(0) t = makeNode.call(Node.Assign, v, e) expect.call("assign", Token.Semi) } else if (tt == Token.While) { token = getTok.call() e = parenExpr.call() s = stmt.call() t = makeNode.call(Node.While, e, s) } else if (tt == Token.Lbrace) { // {stmt} expect.call("Lbrace", Token.Lbrace) while (token.tok != Token.Rbrace && token.tok != Token.EOI) { t = makeNode.call(Node.Sequence, t, stmt.call()) } expect.call("Lbrace", Token.Rbrace) } else if (tt == Token.EOI) { // do nothing } else { reportError.call(token.errLn, token.errCol, Fmt.Swrite("expecting start of statement, found '$s'", atrs[token.tok].text)) } return t }   var parse = Fn.new { var t token = getTok.call() while (true) { t = makeNode.call(Node.Sequence, t, stmt.call()) if (!t || token.tok == Token.EOI) break } return t }   var prtAst // recursive function prtAst = Fn.new { |t| if (!t) { System.print(";") } else { Fmt.write("$-14s ", displayNodes[t.nodeType]) if (t.nodeType == Node.Ident || t.nodeType == Node.Integer || t.nodeType == Node.String) { System.print(t.value) } else { System.print() prtAst.call(t.left) prtAst.call(t.right) } } }   lines = FileUtil.readLines("source.txt") lineCount = lines.count prtAst.call(parse.call())
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.
#Egel
Egel
import "prelude.eg" import "io.ego"   using System using List using IO   def boardsize = 5   def empty = [ X Y -> 0 ]   def insert = [ X Y BOARD -> [ X0 Y0 -> if and (X0 == X) (Y0 == Y) then 1 else BOARD X0 Y0 ] ]   def coords = let R = fromto 0 (boardsize - 1) in [ XX YY -> map (\X -> map (\Y -> X Y) YY) XX ] R R   def printcell = [ 0 -> print ". " | _ -> print "* " ]   def printboard = [ BOARD -> let M = map [XX -> let _ = map [(X Y) -> printcell (BOARD X Y)] XX in print "\n" ] coords in nop ]   def count = [ BOARD, X, Y -> (BOARD (X - 1) (Y - 1)) + (BOARD (X) (Y - 1)) + (BOARD (X+1) (Y - 1)) + (BOARD (X - 1) Y) + (BOARD (X+1) Y) + (BOARD (X - 1) (Y+1)) + (BOARD (X) (Y+1)) + (BOARD (X+1) (Y+1)) ]   def next = [ 0 N -> if N == 3 then 1 else 0 | _ N -> if or (N == 2) (N == 3) then 1 else 0 ]   def updateboard = [ BOARD -> let XX = map (\(X Y) -> X Y (BOARD X Y) (count BOARD X Y)) (flatten coords) in let YY = map (\(X Y C N) -> X Y (next C N)) XX in foldr [(X Y 0) BOARD -> BOARD | (X Y _) BOARD -> insert X Y BOARD ] empty YY ]   def blinker = (insert 1 2) @ (insert 2 2) @ (insert 3 2)   def main = let GEN0 = blinker empty in let GEN1 = updateboard GEN0 in let GEN2 = updateboard GEN1 in let _ = map [ G -> let _ = print "generation:\n" in printboard G ] {GEN0, GEN1, GEN2} in nop  
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#SIMPOL
SIMPOL
type mypoint embed integer x integer y end type
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#SNOBOL4
SNOBOL4
data('point(x,y)') p1 = point(10,20) p2 = point(10,40) output = "Point 1 (" x(p1) "," y(p1) ")" output = "Point 2 (" x(p2) "," y(p2) ")" 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.
#Befunge
Befunge
v > "X",@ non-zero > & | > "0",@ zero
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   The author has two Z$100000000000000 Zimbabwe notes (100 trillion).   "-in Aus$+1411.8millions"   ===US$0017440 millions=== (in 2000 dollars)   123.e8000 is pretty big.   The land area of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#VBA
VBA
Public Sub commatize(s As String, Optional sep As String = ",", Optional start As Integer = 1, Optional step As Integer = 3) Dim l As Integer: l = Len(s) For i = start To l If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then For j = i + 1 To l + 1 If j > l Then For k = j - 1 - step To i Step -step s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1) l = Len(s) Next k Exit For Else If (Asc(Mid(s, j, 1)) < Asc("0") Or Asc(Mid(s, j, 1)) > Asc("9")) Then For k = j - 1 - step To i Step -step s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1) l = Len(s) Next k Exit For End If End If Next j Exit For End If Next i Debug.Print s End Sub Public Sub main() commatize "pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 6, 5 commatize "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "." commatize """-in Aus$+1411.8millions""" commatize "===US$0017440 millions=== (in 2000 dollars)" commatize "123.e8000 is pretty big." commatize "The land area of the earth is 57268900(29% of the surface) square miles." commatize "Ain't no numbers in this here words, nohow, no way, Jose." commatize "James was never known as 0000000007" commatize "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." commatize " $-140000±100 millions." commatize "6/9/1946 was a good year for some." End Sub
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   The author has two Z$100000000000000 Zimbabwe notes (100 trillion).   "-in Aus$+1411.8millions"   ===US$0017440 millions=== (in 2000 dollars)   123.e8000 is pretty big.   The land area of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#Wren
Wren
var commatize = Fn.new { |s, start, step, sep| var addSeps = Fn.new { |n, dp| var lz = "" if (!dp && n.startsWith("0") && n != "0") { var k = n.trimStart("0") if (k == "") k = "0" lz = "0" * (n.count - k.count) n = k } if (dp) n = n[-1..0] // invert if after decimal point var i = n.count - step while (i >= 1) { n = n[0...i] + sep + n[i..-1] i = i - step } if (dp) n = n[-1..0] // invert back return lz + n }   var t = s.toList var isExponent = Fn.new { |c| "eEdDpP^∙x↑*⁰¹²³⁴⁵⁶⁷⁸⁹".contains(c) } var acc = (start == 0) ? "" : t.toList[0...start].join() var n = "" var dp = false for (j in start...t.count) { var c = t[j].codePoints[0] if (c >= 48 && c <= 57) { n = n + t[j] if (j == t.count-1) { if (acc != "" && isExponent.call(acc[-1])) { acc = s } else { acc = acc + addSeps.call(n, dp) } } } else if (n != "") { if (acc != "" && isExponent.call(acc[-1])) { acc = s break } else if (t[j] != ".") { acc = acc + addSeps.call(n, dp) + t[j..-1].join() break } else { acc = acc + addSeps.call(n, dp) + t[j] dp = true n = "" } } else { acc = acc + t[j] } }   System.print(s) System.print(acc) System.print() }   // special version of the above which uses defaults for start, step and sep. var commatize2 = Fn.new { |s| commatize.call(s, 0, 3, ",") }   commatize.call("123456789.123456789", 0, 2, "*") commatize.call(".123456789", 0, 3, "-") commatize.call("57256.1D-4", 0, 4, "__") commatize.call("pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " ") commatize.call("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, ".")   var defaults = [ "\"-in Aus$+1411.8millions\"", "===US$0017440 millions=== (in 2000 dollars)", "123.e8000 is pretty big.", "The land area of the earth is 57268900(29\% of the surface) square miles.", "Ain't no numbers in this here words, nohow, no way, Jose.", "James was never known as 0000000007", "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.", " $-140000±100 millions.", "6/9/1946 was a good year for some." ]   defaults.each { |d| commatize2.call(d) }
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
#F.23
F#
let allEqual strings = Seq.isEmpty strings || Seq.forall (fun x -> x = Seq.head strings) (Seq.tail strings) let ascending strings = Seq.isEmpty strings || Seq.forall2 (fun x y -> x < y) strings (Seq.tail strings)
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
#Factor
Factor
USE: grouping all-equal?
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.
#BCPL
BCPL
get "libhdr"   // Add a character to the end of a string let addch(s, ch) be $( s%0 := s%0 + 1 s%(s%0) := ch $) // Add s2 to the end of s1 and adds(s1, s2) be for i = 1 to s2%0 do addch(s1, s2%i)   // Comma quibbling on strs, which should be a 0-terminated // vector of string pointers. let quibble(strs, buf) = valof $( buf%0 := 0 addch(buf, '{') until !strs = 0 do $( addch(buf, '"') adds(buf, !strs) addch(buf, '"') unless strs!1 = 0 test strs!2 = 0 then adds(buf, " and ") else adds(buf, ", ") strs := strs + 1 $) addch(buf, '}') resultis buf $)   let start() be $( let words = vec 4 let buf = vec 63   words!0 := 0 writef("%S*N", quibble(words, buf))   words!0 := "ABC" ; words!1 := 0 writef("%S*N", quibble(words, buf))   words!1 := "DEF" ; words!2 := 0 writef("%S*N", quibble(words, buf))   words!2 := "G" ; words!3 := "H" ; words!4 := 0 writef("%S*N", quibble(words, buf)) $)
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.
#Bracmat
Bracmat
( :?L1 & ABC:?L2 & ABC DEF:?L3 & ABC DEF G H:?L4 & L1 L2 L3 L4:?names & ( quibble = w .  !arg:%?w (% %:?arg) & !w ", " quibble$!arg | !arg:%?w %?arg&!w " and " quibble$!arg | !arg ) & (concat=.str$("{" quibble$!arg "}")) & whl ' (!names:%?name ?names&out$(!name concat$!!name)) );
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#C.2B.2B
C++
  #include <iostream> #include <string> #include <vector>   void print_vector(const std::vector<int> &pos, const std::vector<std::string> &str) { for (size_t i = 1; i < pos.size(); ++i) // offset: i:1..N printf("%s\t", str[pos[i]].c_str()); // str: 0..N-1 printf("\n"); }   // idea: custom number system with 2s complement like 0b10...0==MIN stop case void combination_with_repetiton(int n, int k, const std::vector<std::string> &str) { std::vector<int> pos(k + 1, 0); while (true) { for (int i = k; i > 0; i -= 1) { if (pos[i] > n - 1) // if number spilled over: xx0(n-1)xx { pos[i - 1] += 1; // set xx1(n-1)xx for (int j = i; j <= k; j += 1) pos[j] = pos[j - 1]; // set xx11..1 } } if (pos[0] > 0) // stop condition: 1xxxx break; print_vector(pos, str); pos[k] += 1; // xxxxN -> xxxxN+1 } }   int main() { std::vector<std::string> str{"iced", "jam", "plain"}; combination_with_repetiton(3, 2, str); return 0; }  
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Go
Go
  package main   import ( "fmt" "math/big" )   func main() { var n, p int64 fmt.Printf("A sample of permutations from 1 to 12:\n") for n = 1; n < 13; n++ { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 10 to 60:\n") for n = 10; n < 61; n += 10 { p = n / 3 fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of permutations from 5 to 15000:\n") nArr := [...]int64{5, 50, 500, 1000, 5000, 15000} for _, n = range nArr { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 100 to 1000:\n") for n = 100; n < 1001; n += 100 { p = n / 3 fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) } }   func fact(n *big.Int) *big.Int { if n.Sign() < 1 { return big.NewInt(0) } r := big.NewInt(1) i := big.NewInt(2) for i.Cmp(n) < 1 { r.Mul(r, i) i.Add(i, big.NewInt(1)) } return r }   func perm(n, k *big.Int) *big.Int { r := fact(n) r.Div(r, fact(n.Sub(n, k))) return r }   func comb(n, r *big.Int) *big.Int { if r.Cmp(n) == 1 { return big.NewInt(0) } if r.Cmp(n) == 0 { return big.NewInt(1) } c := fact(n) den := fact(n.Sub(n, r)) den.Mul(den, fact(r)) c.Div(c, den) return c }  
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
#Emacs_Lisp
Emacs Lisp
#!/usr/bin/emacs --script ;; ;; The Rosetta Code lexical analyzer in GNU Emacs Lisp. ;; ;; Migrated from the ATS. However, Emacs Lisp is not friendly to the ;; functional style of the ATS implementation; therefore the ;; differences are vast. ;; ;; (A Scheme migration could easily, on the other hand, have been ;; almost exact. It is interesting to contrast Lisp dialects and see ;; how huge the differences are.) ;; ;; The script currently takes input only from standard input and ;; writes the token stream only to standard output. ;;   (require 'cl-lib)   ;;; The type of a character, consisting of its code point and where it ;;; occurred in the text. (cl-defstruct (ch_t (:constructor make-ch (ichar line-no column-no))) ichar line-no column-no)   (defun ch-ichar (ch) (ch_t-ichar ch))   (defun ch-line-no (ch) (ch_t-line-no ch))   (defun ch-column-no (ch) (ch_t-column-no ch))   ;;; The type of an "inputter", consisting of an open file for the ;;; text, a pushback buffer (which is an indefinitely deep stack of ;;; ch_t), an input buffer for the current line, and a position in the ;;; text. (cl-defstruct inp_t file pushback line line-no column-no)   (defun make-inp (file) "Initialize a new inp_t." (make-inp_t :file file :pushback '() :line "" :line-no 0 :column-no 0))   (defvar inp (make-inp t) "A global inp_t.")   (defun get-ch () "Get a ch_t, either from the pushback buffer or from the input." (pcase (inp_t-pushback inp) (`(,ch . ,tail) ;; Emacs Lisp has only single value return, so the results come ;; back as a list rather than multiple values. (setq inp (make-inp_t :file (inp_t-file inp) :pushback tail :line (inp_t-line inp) :line-no (inp_t-line-no inp) :column-no (inp_t-column-no inp))) ch) ('() (let ((line (inp_t-line inp)) (line-no (inp_t-line-no inp)) (column-no (inp_t-column-no inp))) (when (string= line "") ;; Refill the buffer. (let ((text (condition-case nil (read-string "") nil (error 'eoi)))) (if (eq text 'eoi) (setq line 'eoi) (setq line (format "%s%c" text ?\n))) (setq line-no (1+ line-no)) (setq column-no 1))) (if (eq line 'eoi) (progn (setq inp (make-inp_t :file (inp_t-file inp) :pushback (inp_t-pushback inp) :line line :line-no line-no :column-no column-no)) (make-ch 'eoi line-no column-no)) (let ((c (elt line 0)) (line (substring line 1))) (setq inp (make-inp_t :file (inp_t-file inp) :pushback (inp_t-pushback inp) :line line :line-no line-no :column-no (1+ column-no))) (make-ch c line-no column-no)))))))   (defun get-new-line (file) ;; Currently "file" is ignored and the input must be from stdin. (read-from-minibuffer "" :default 'eoi))   (defun push-back (ch) "Push back a ch_t." (setq inp (make-inp_t :file (inp_t-file inp) :pushback (cons ch (inp_t-pushback inp)) :line (inp_t-line inp) :line-no (inp_t-line-no inp) :column-no (inp_t-column-no inp))))   (defun get-position () "Return the line-no and column-no of the next ch_t to be returned by get-ch, assuming there are no more pushbacks beforehand." (let* ((ch (get-ch)) (line-no (ch-line-no ch)) (column-no (ch-column-no ch))) (push-back ch) (list line-no column-no)))   (defun scan-text (outf) "The main loop." (cl-loop for toktup = (get-next-token) do (print-token outf toktup) until (string= (elt toktup 0) "End_of_input")))   (defun print-token (outf toktup) "Print a token, along with its position and possibly an argument." ;; Currently outf is ignored, and the output goes to stdout. (pcase toktup (`(,tok ,arg ,line-no ,column-no) (princ (format "%5d %5d  %s" line-no column-no tok)) (pcase tok ("Identifier" (princ (format "  %s\n" arg))) ("Integer" (princ (format "  %s\n" arg))) ("String" (princ (format "  %s\n" arg))) (_ (princ "\n"))))))   (defun get-next-token () "The token dispatcher. Returns the next token, as a list along with its argument and text position." (skip-spaces-and-comments) (let* ((ch (get-ch)) (ln (ch-line-no ch)) (cn (ch-column-no ch))) (pcase (ch-ichar ch) ('eoi (list "End_of_input" "" ln cn)) (?, (list "Comma" "," ln cn)) (?\N{SEMICOLON} (list "Semicolon" ";" ln cn)) (?\N{LEFT PARENTHESIS} (list "LeftParen" "(" ln cn)) (?\N{RIGHT PARENTHESIS} (list "RightParen" ")" ln cn)) (?{ (list "LeftBrace" "{" ln cn)) (?} (list "RightBrace" "}" ln cn)) (?* (list "Op_multiply" "*" ln cn)) (?/ (list "Op_divide" "/" ln cn)) (?% (list "Op_mod" "%" ln cn)) (?+ (list "Op_add" "+" ln cn)) (?- (list "Op_subtract" "-" ln cn)) (?< (let ((ch1 (get-ch))) (pcase (ch-ichar ch1) (?= (list "Op_lessequal" "<=" ln cn)) (_ (push-back ch1) (list "Op_less" "<" ln cn))))) (?> (let ((ch1 (get-ch))) (pcase (ch-ichar ch1) (?= (list "Op_greaterequal" ">=" ln cn)) (_ (push-back ch1) (list "Op_greater" ">" ln cn))))) (?= (let ((ch1 (get-ch))) (pcase (ch-ichar ch1) (?= (list "Op_equal" "==" ln cn)) (_ (push-back ch1) (list "Op_assign" "=" ln cn))))) (?! (let ((ch1 (get-ch))) (pcase (ch-ichar ch1) (?= (list "Op_notequal" "!=" ln cn)) (_ (push-back ch1) (list "Op_not" "!" ln cn))))) (?& (let ((ch1 (get-ch))) (pcase (ch-ichar ch1) (?& (list "Op_and" "&&" ln cn)) (_ (unexpected-character ln cn (get-ichar ch)))))) (?| (let ((ch1 (get-ch))) (pcase (ch-ichar ch1) (?| (list "Op_or" "||" ln cn)) (_ (unexpected-character ln cn (get-ichar ch)))))) (?\N{QUOTATION MARK} (push-back ch) (scan-string-literal)) (?\N{APOSTROPHE} (push-back ch) (scan-character-literal)) ((pred digitp) (push-back ch) (scan-integer-literal)) ((pred identifier-start-p) (progn (push-back ch) (scan-identifier-or-reserved-word))) (c (unexpected-character ln cn c)))))   (defun skip-spaces-and-comments () "Skip spaces and comments. A comment is treated as equivalent to a run of spaces." (cl-loop for ch = (let ((ch1 (get-ch))) (pcase (ch-ichar ch1) (?/ (let* ((ch2 (get-ch)) (line-no (ch-line-no ch1)) (column-no (ch-column-no ch1)) (position `(,line-no ,column-no))) (pcase (ch-ichar ch2) (?* (scan-comment position) (get-ch)) (_ (push-back ch2) ch1)))) (_ ch1))) while (spacep (ch-ichar ch)) finally do (push-back ch)))   (defun scan-comment (position) (cl-loop for ch = (get-ch) for done = (comment-done-p ch position) until done))   (defun comment-done-p (ch position) (pcase (ch-ichar ch) ('eoi (apply 'unterminated-comment position)) (?* (let ((ch1 (get-ch))) (pcase (ch-ichar ch1) ('eoi (apply 'unterminated-comment position)) (?/ t) (_ nil)))) (_ nil)))   (defun scan-integer-literal () "Scan an integer literal, on the assumption that a digit has been seen and pushed back." (let* ((position (get-position)) (lst (scan-word)) (s (list-to-string lst))) (if (all-digits-p lst) `("Integer" ,s . ,position) (apply 'illegal-integer-literal `(,@position , s)))))   (defun scan-identifier-or-reserved-word () "Scan an identifier or reserved word, on the assumption that a legal first character (for an identifier) has been seen and pushed back." (let* ((position (get-position)) (lst (scan-word)) (s (list-to-string lst)) (tok (pcase s ("else" "Keyword_else") ("if" "Keyword_if") ("while" "Keyword_while") ("print" "Keyword_print") ("putc" "Keyword_putc") (_ "Identifier")))) `(,tok ,s . ,position)))   (defun scan-word () (cl-loop for ch = (get-ch) while (identifier-continuation-p (ch-ichar ch)) collect (ch-ichar ch) finally do (push-back ch)))   (defun scan-string-literal () "Scan a string literal, on the assumption that a double quote has been seen and pushed back." (let* ((ch (get-ch)) (_ (cl-assert (= (ch-ichar ch) ?\N{QUOTATION MARK}))) (line-no (ch-line-no ch)) (column-no (ch-column-no ch)) (position `(,line-no ,column-no)) (lst (scan-str-lit position)) (lst `(?\N{QUOTATION MARK} ,@lst ?\N{QUOTATION MARK}))) `("String" ,(list-to-string lst) . ,position)))   (defun scan-str-lit (position) (flatten (cl-loop for ch = (get-ch) until (= (ch-ichar ch) ?\N{QUOTATION MARK}) collect (process-str-lit-character (ch-ichar ch) position))))   (defun process-str-lit-character (c position) ;; NOTE: This script might insert a newline before any eoi, so that ;; "end-of-input-in-string-literal" never actually occurs. It is a ;; peculiarity of the script's input mechanism. (pcase c ('eoi (apply 'end-of-input-in-string-literal position)) (?\n (apply 'end-of-line-in-string-literal position)) (?\\ (let ((ch1 (get-ch))) (pcase (ch-ichar ch1) (?n '(?\\ ?n)) (?\\ '(?\\ ?\\)) (c (unsupported-escape (ch-line-no ch1) (ch-column-no ch1) c))))) (c c)))   (defun scan-character-literal () "Scan a character literal, on the assumption that an ASCII single quote (that is, a Unicode APOSTROPHE) has been seen and pushed back." (let* ((toktup (scan-character-literal-without-checking-end)) (line-no (elt toktup 2)) (column-no (elt toktup 3)) (position (list line-no column-no))) (check-char-lit-end position) toktup))   (defun check-char-lit-end (position) (let ((ch (get-ch))) (unless (and (integerp (ch-ichar ch)) (= (ch-ichar ch) ?\N{APOSTROPHE})) (push-back ch) (loop-to-char-lit-end position))))   (defun loop-to-char-lit-end (position) (cl-loop for ch = (get-ch) until (or (eq (ch-ichar ch) 'eoi) (= (ch-ichar ch) ?\N{APOSTROPHE})) finally do (if (eq (ch-ichar ch) 'eoi) (apply 'unterminated-character-literal position) (apply 'multicharacter-literal position))))   (defun scan-character-literal-without-checking-end () (let* ((ch (get-ch)) (_ (cl-assert (= (ch-ichar ch) ?\N{APOSTROPHE}))) (line-no (ch-line-no ch)) (column-no (ch-column-no ch)) (position (list line-no column-no)) (ch1 (get-ch))) (pcase (ch-ichar ch1) ('eoi (apply 'unterminated-character-literal position)) (?\\ (let ((ch2 (get-ch))) (pcase (ch-ichar ch2) ('eoi (apply 'unterminated-character-literal position)) (?n `("Integer" ,(format "%d" ?\n) . ,position)) (?\\ `("Integer" ,(format "%d" ?\\) . ,position)) (c (unsupported-escape (ch-line-no ch1) (ch-column-no ch1) c))))) (c `("Integer" ,(format "%d" c) . ,position)))))   (defun spacep (c) (and (integerp c) (or (= c ?\N{SPACE}) (and (<= 9 c) (<= c 13)))))   (defun digitp (c) (and (integerp c) (<= ?0 c) (<= c ?9)))   (defun lowerp (c) ;; Warning: in EBCDIC, this kind of test for "alphabetic" is no ;; good. The letters are not contiguous. (and (integerp c) (<= ?a c) (<= c ?z)))   (defun upperp (c) ;; Warning: in EBCDIC, this kind of test for "alphabetic" is no ;; good. The letters are not contiguous. (and (integerp c) (<= ?A c) (<= c ?Z)))   (defun alphap (c) (or (lowerp c) (upperp c)))   (defun identifier-start-p (c) (and (integerp c) (or (alphap c) (= c ?_))))   (defun identifier-continuation-p (c) (and (integerp c) (or (alphap c) (= c ?_) (digitp c))))   (defun all-digits-p (thing) (cl-loop for c in thing if (not (digitp c)) return nil finally return t))   (defun list-to-string (lst) "Convert a list of characters to a string." (apply 'string lst))   (defun flatten (lst) "Flatten nested lists. (The implementation is recursive and not for very long lists.)" (pcase lst ('() '()) (`(,head . ,tail) (if (listp head) (append (flatten head) (flatten tail)) (cons head (flatten tail))))))   (defun unexpected-character (line-no column-no c) (error (format "unexpected character '%c' at %d:%d" c line-no column-no)))   (defun unsupported-escape (line-no column-no c) (error (format "unsupported escape \\%c at %d:%d" c line-no column-no)))   (defun illegal-integer-literal (line-no column-no s) (error (format "illegal integer literal \"%s\" at %d:%d" s line-no column-no)))   (defun unterminated-character-literal (line-no column-no) (error (format "unterminated character literal starting at %d:%d" line-no column-no)))   (defun multicharacter-literal (line-no column-no) (error (format "unsupported multicharacter literal starting at %d:%d" line-no column-no)))   (defun end-of-input-in-string-literal (line-no column-no) (error (format "end of input in string literal starting at %d:%d" line-no column-no)))   (defun end-of-line-in-string-literal (line-no column-no) (error (format "end of line in string literal starting at %d:%d" line-no column-no)))   (defun unterminated-comment (line-no column-no) (error (format "unterminated comment starting at %d:%d" line-no column-no)))   (defun main () (setq inp (make-inp t)) (scan-text t))   (main)
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"
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. accept-all-args.   DATA DIVISION. WORKING-STORAGE SECTION. 01 args PIC X(50).   PROCEDURE DIVISION. main-line. ACCEPT args FROM COMMAND-LINE DISPLAY args   GOBACK .
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"
#CoffeeScript
CoffeeScript
  console.log arg for arg in process.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.)
#Asymptote
Asymptote
// double slash to newline
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.)
#AutoHotkey
AutoHotkey
Msgbox, comments demo ; end of line comment /* multiline comment1 multiline comment2 */
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#Python
Python
from __future__ import print_function import sys, struct   FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, \ JMP, JZ, PRTC, PRTS, PRTI, HALT = range(24)   code_map = { "fetch": FETCH, "store": STORE, "push": PUSH, "add": ADD, "sub": SUB, "mul": MUL, "div": DIV, "mod": MOD, "lt": LT, "gt": GT, "le": LE, "ge": GE, "eq": EQ, "ne": NE, "and": AND, "or": OR, "not": NOT, "neg": NEG, "jmp": JMP, "jz": JZ, "prtc": PRTC, "prts": PRTS, "prti": PRTI, "halt": HALT }   input_file = None code = bytearray() string_pool = [] word_size = 4   #*** show error and exit def error(msg): print("%s" % (msg)) exit(1)   def int_to_bytes(val): return struct.pack("<i", val)   def bytes_to_int(bstr): return struct.unpack("<i", bstr)   #*** def emit_byte(x): code.append(x)   #*** def emit_word(x): s = int_to_bytes(x) for x in s: code.append(x)   #*** def run_vm(data_size): stack = [0 for i in range(data_size + 1)] pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() # use C like division semantics elif op == DIV: stack[-2] = int(float(stack[-2]) / stack[-1]); stack.pop() elif op == MOD: stack[-2] = int(float(stack[-2]) % stack[-1]); stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop(): pc += word_size else: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print("%c" % (stack[-1]), end=''); stack.pop() elif op == PRTS: print("%s" % (string_pool[stack[-1]]), end=''); stack.pop() elif op == PRTI: print("%d" % (stack[-1]), end=''); stack.pop() elif op == HALT: break   def str_trans(srce): dest = "" i = 0 while i < len(srce): if srce[i] == '\\' and i + 1 < len(srce): if srce[i + 1] == 'n': dest += '\n' i += 2 elif srce[i + 1] == '\\': dest += '\\' i += 2 else: dest += srce[i] i += 1   return dest   #*** def load_code(): global string_pool   line = input_file.readline() if len(line) == 0: error("empty line")   line_list = line.split() data_size = int(line_list[1]) n_strings = int(line_list[3])   for i in range(n_strings): string_pool.append(str_trans(input_file.readline().strip('"\n')))   while True: line = input_file.readline() if len(line) == 0: break line_list = line.split() offset = int(line_list[0]) instr = line_list[1] opcode = code_map.get(instr) if opcode == None: error("Unknown instruction %s at %d" % (instr, offset)) emit_byte(opcode) if opcode in [JMP, JZ]: p = int(line_list[3]) emit_word(p - (offset + 1)) elif opcode == PUSH: value = int(line_list[2]) emit_word(value) elif opcode in [FETCH, STORE]: value = int(line_list[2].strip('[]')) emit_word(value)   return data_size   #*** main driver input_file = sys.stdin if len(sys.argv) > 1: try: input_file = open(sys.argv[1], "r", 4096) except IOError as e: error(0, 0, "Can't open %s" % sys.argv[1])   data_size = load_code() run_vm(data_size)
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#Raku
Raku
my %opnames = < Less lt LessEqual le Multiply mul Subtract sub NotEqual ne Divide div GreaterEqual ge Equal eq Greater gt Negate neg >;   my (@AST, %strings, %names); my $string-count = my $name-count = my $pairsym = my $pc = 0;   sub tree { my ($A, $B) = ( '_' ~ ++$pairsym, '_' ~ ++$pairsym ); my $line = @AST.shift // return ''; $line ~~ /^ $<instr> = (\w+|';') [\s+ $<arg> =(.*)]? / or die "bad input $line"; given $<instr> { when 'Identifier' { "fetch [{%names{$<arg>} //= $name-count++ }]\n" } when 'Sequence' { tree() ~ tree() } when 'Integer' { "push $<arg>\n" } when 'String' { "push { %strings{$<arg>} //= $string-count++ }\n" } when 'Assign' { join '', reverse (tree().subst( /fetch/, 'store')), tree() } when 'While' { "$A:\n{ tree() }jz $B\n{ tree() }jmp $A\n$B:\n" } when 'If' { tree() ~ "jz $A\n{ [email protected] ~ tree() }jmp $B\n$A:\n{ tree() }$B:\n" } when ';' { '' } default { tree() ~ tree() ~ (%opnames{$<instr>} // $<instr>.lc) ~ "\n" } } }   @AST = slurp('ast.txt').lines; my $code = tree() ~ "halt\n";   $code ~~ s:g/^^ jmp \s+ (\S+) \n ('_'\d+:\n) $0:\n/$1/; # remove jmp next $code ~~ s:g/^^ (<[a..z]>\w* (\N+)? ) $$/{my $l=$pc.fmt("%4d "); $pc += $0[0] ?? 5 !! 1; $l}$0/; # add locations my %labels = ($code ~~ m:g/^^ ('_' \d+) ':' \n \s* (\d+)/)».Slip».Str; # pc addr of labels $code ~~ s:g/^^ \s* (\d+) \s j[z|mp] \s* <(('_'\d+)/ ({%labels{$1} - $0 - 1}) %labels{$1}/; # fix jumps $code ~~ s:g/^^ '_'\d+.*?\n//; # remove labels   say "Datasize: $name-count Strings: $string-count\n" ~ join('', %strings.keys.sort.reverse «~» "\n") ~ $code;
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Python
Python
A = 'I am string' B = 'I am string too'   if len(A) > len(B): print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings') print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings') elif len(A) < len(B): print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings') print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings') else: print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string') print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#QB64
QB64
  Dim Words(1 To 4) As String Dim Lengths As Integer, Index As Integer, Position As Integer, Done As String, Index2 As Integer ' inititialization Words(1) = "abcd" Words(2) = "123456789" Words(3) = "abcdef" Words(4) = "1234567"   Print " Word Length" For Index2 = 1 To 4 Step 1 Lengths = 0 Position = 0 For Index = 1 To 4 Step 1 If Lengths < Len(Words(Index)) And InStr(Done, Words(Index) + " ") = 0 Then Lengths = Len(Words(Index)) Position = Index End If Next Index Done = Done + Words(Position) + " /@/" Print Words(Position), Len(Words(Position)) Next Index2  
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a parser module/library/class, it would be great if two versions of the solution are provided: One without the parser module, and one with. Grammar The simple programming language to be analyzed is more or less a (very tiny) subset of C. The formal grammar in Extended Backus-Naur Form (EBNF):   stmt_list = {stmt} ;   stmt = ';' | Identifier '=' expr ';' | 'while' paren_expr stmt | 'if' paren_expr stmt ['else' stmt] | 'print' '(' prt_list ')' ';' | 'putc' paren_expr ';' | '{' stmt_list '}'  ;   paren_expr = '(' expr ')' ;   prt_list = (string | expr) {',' (String | expr)} ;   expr = and_expr {'||' and_expr} ; and_expr = equality_expr {'&&' equality_expr} ; equality_expr = relational_expr [('==' | '!=') relational_expr] ; relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ; addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ; multiplication_expr = primary {('*' | '/' | '%') primary } ; primary = Identifier | Integer | '(' expr ')' | ('+' | '-' | '!') primary  ; The resulting AST should be formulated as a Binary Tree. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast The following table shows the input to lex, lex output, and the AST produced by the parser Input to lex Output from lex, input to parse Output from parse count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Specifications List of node type names Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or In the text below, Null/Empty nodes are represented by ";". Non-terminal (internal) nodes For Operators, the following nodes should be created: Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or For each of the above nodes, the left and right sub-nodes are the operands of the respective operation. In pseudo S-Expression format: (Operator expression expression) Negate, Not For these node types, the left node is the operand, and the right node is null. (Operator expression ;) Sequence - sub-nodes are either statements or Sequences. If - left node is the expression, the right node is If node, with it's left node being the if-true statement part, and the right node being the if-false (else) statement part. (If expression (If statement else-statement)) If there is not an else, the tree becomes: (If expression (If statement ;)) Prtc (Prtc (expression) ;) Prts (Prts (String "the string") ;) Prti (Prti (Integer 12345) ;) While - left node is the expression, the right node is the statement. (While expression statement) Assign - left node is the left-hand side of the assignment, the right node is the right-hand side of the assignment. (Assign Identifier expression) Terminal (leaf) nodes: Identifier: (Identifier ident_name) Integer: (Integer 12345) String: (String "Hello World!") ";": Empty node Some simple examples Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path. This simple program: a=11; Produces the following AST, encoded as a binary tree: Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node: (1) Sequence (2) |-- ; (3) |-- Assign (4) |-- Identifier: a (5) |-- Integer: 11 In flattened form: (1) Sequence (2) ; (3) Assign (4) Identifier a (5) Integer 11 This program: a=11; b=22; c=33; Produces the following AST: ( 1) Sequence ( 2) |-- Sequence ( 3) | |-- Sequence ( 4) | | |-- ; ( 5) | | |-- Assign ( 6) | | |-- Identifier: a ( 7) | | |-- Integer: 11 ( 8) | |-- Assign ( 9) | |-- Identifier: b (10) | |-- Integer: 22 (11) |-- Assign (12) |-- Identifier: c (13) |-- Integer: 33 In flattened form: ( 1) Sequence ( 2) Sequence ( 3) Sequence ( 4) ; ( 5) Assign ( 6) Identifier a ( 7) Integer 11 ( 8) Assign ( 9) Identifier b (10) Integer 22 (11) Assign (12) Identifier c (13) Integer 33 Pseudo-code for the parser. Uses Precedence Climbing for expression parsing, and Recursive Descent for statement parsing. The AST is also built: def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error()   while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q))   return x   def paren_expr() expect("(") x = expr(0) expect(")") return x   def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0))   t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t   def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t Once the AST is built, it should be output in a flattened format. This can be as simple as the following def prt_ast(t) if t == NULL print(";\n") else print(t.node_type) if t.node_type in [Identifier, Integer, String] # leaf node print the value of the Ident, Integer or String, "\n" else print("\n") prt_ast(t.left) prt_ast(t.right) If the AST is correctly built, loading it into a subsequent program should be as simple as def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) Finally, the AST can also be tested by running it against one of the AST Interpreter solutions. Test program, assuming this is in a file called prime.t lex <prime.t | parse Input to lex Output from lex, input to parse Output from parse /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 4 1 Identifier count 4 7 Op_assign 4 9 Integer 1 4 10 Semicolon 5 1 Identifier n 5 3 Op_assign 5 5 Integer 1 5 6 Semicolon 6 1 Identifier limit 6 7 Op_assign 6 9 Integer 100 6 12 Semicolon 7 1 Keyword_while 7 7 LeftParen 7 8 Identifier n 7 10 Op_less 7 12 Identifier limit 7 17 RightParen 7 19 LeftBrace 8 5 Identifier k 8 6 Op_assign 8 7 Integer 3 8 8 Semicolon 9 5 Identifier p 9 6 Op_assign 9 7 Integer 1 9 8 Semicolon 10 5 Identifier n 10 6 Op_assign 10 7 Identifier n 10 8 Op_add 10 9 Integer 2 10 10 Semicolon 11 5 Keyword_while 11 11 LeftParen 11 12 LeftParen 11 13 Identifier k 11 14 Op_multiply 11 15 Identifier k 11 16 Op_lessequal 11 18 Identifier n 11 19 RightParen 11 21 Op_and 11 24 LeftParen 11 25 Identifier p 11 26 RightParen 11 27 RightParen 11 29 LeftBrace 12 9 Identifier p 12 10 Op_assign 12 11 Identifier n 12 12 Op_divide 12 13 Identifier k 12 14 Op_multiply 12 15 Identifier k 12 16 Op_notequal 12 18 Identifier n 12 19 Semicolon 13 9 Identifier k 13 10 Op_assign 13 11 Identifier k 13 12 Op_add 13 13 Integer 2 13 14 Semicolon 14 5 RightBrace 15 5 Keyword_if 15 8 LeftParen 15 9 Identifier p 15 10 RightParen 15 12 LeftBrace 16 9 Keyword_print 16 14 LeftParen 16 15 Identifier n 16 16 Comma 16 18 String " is prime\n" 16 31 RightParen 16 32 Semicolon 17 9 Identifier count 17 15 Op_assign 17 17 Identifier count 17 23 Op_add 17 25 Integer 1 17 26 Semicolon 18 5 RightBrace 19 1 RightBrace 20 1 Keyword_print 20 6 LeftParen 20 7 String "Total primes found: " 20 29 Comma 20 31 Identifier count 20 36 Comma 20 38 String "\n" 20 42 RightParen 20 43 Semicolon 21 1 End_of_input Sequence Sequence Sequence Sequence Sequence ; Assign Identifier count Integer 1 Assign Identifier n Integer 1 Assign Identifier limit Integer 100 While Less Identifier n Identifier limit Sequence Sequence Sequence Sequence Sequence ; Assign Identifier k Integer 3 Assign Identifier p Integer 1 Assign Identifier n Add Identifier n Integer 2 While And LessEqual Multiply Identifier k Identifier k Identifier n Identifier p Sequence Sequence ; Assign Identifier p NotEqual Multiply Divide Identifier n Identifier k Identifier k Identifier n Assign Identifier k Add Identifier k Integer 2 If Identifier p If Sequence Sequence ; Sequence Sequence ; Prti Identifier n ; Prts String " is prime\n" ; Assign Identifier count Add Identifier count Integer 1 ; Sequence Sequence Sequence ; Prts String "Total primes found: " ; Prti Identifier count ; Prts String "\n" ; Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#Zig
Zig
  const std = @import("std");   pub const NodeValue = union(enum) { integer: i32, string: []const u8,   fn fromToken(token: Token) ?NodeValue { if (token.value) |value| { switch (value) { .integer => |int| return NodeValue{ .integer = int }, .string => |str| return NodeValue{ .string = str }, } } else { return null; } } };   pub const Tree = struct { left: ?*Tree, right: ?*Tree, typ: NodeType, value: ?NodeValue = null, };   pub const ParserError = error{ OutOfMemory, ExpectedNotFound, } || std.fmt.ParseIntError;   pub const Parser = struct { token_it: LexerOutputTokenizer, curr: Token, allocator: std.mem.Allocator,   const Self = @This();   pub fn init(allocator: std.mem.Allocator, str: []const u8) Self { return Self{ .token_it = LexerOutputTokenizer.init(str), .curr = Token{ .line = 0, .col = 0, .typ = .unknown }, .allocator = allocator, }; }   fn makeNode(self: *Self, typ: NodeType, left: ?*Tree, right: ?*Tree) !*Tree { const result = try self.allocator.create(Tree); result.* = Tree{ .left = left, .right = right, .typ = typ }; return result; }   fn makeLeaf(self: *Self, typ: NodeType, value: ?NodeValue) !*Tree { const result = try self.allocator.create(Tree); result.* = Tree{ .left = null, .right = null, .typ = typ, .value = value }; return result; }   pub fn parse(self: *Self) ParserError!?*Tree { try self.next(); var result: ?*Tree = null; while (true) { const stmt = try self.parseStmt(); result = try self.makeNode(.sequence, result, stmt); if (self.curr.typ == .eof) break; } return result; }   /// Classic "Recursive descent" statement parser. fn parseStmt(self: *Self) ParserError!?*Tree { var result: ?*Tree = null; switch (self.curr.typ) { .kw_print => { try self.next(); try self.expect(.left_paren); // Parse each print's argument as an expression delimited by commas until we reach // a closing parens. while (true) { var expr: ?*Tree = null; if (self.curr.typ == .string) { expr = try self.makeNode( .prts, try self.makeLeaf(.string, NodeValue.fromToken(self.curr)), null, ); try self.next(); } else { expr = try self.makeNode(.prti, try self.parseExpr(0), null); } result = try self.makeNode(.sequence, result, expr); if (self.curr.typ != .comma) break; try self.next(); } try self.expect(.right_paren); try self.expect(.semicolon); }, .kw_putc => { try self.next(); result = try self.makeNode(.prtc, try self.parseParenExpr(), null); try self.expect(.semicolon); }, .kw_while => { try self.next(); const expr = try self.parseParenExpr(); result = try self.makeNode(.kw_while, expr, try self.parseStmt()); }, .kw_if => { try self.next(); const expr = try self.parseParenExpr(); const if_stmt = try self.parseStmt(); const else_stmt = blk: { if (self.curr.typ == .kw_else) { try self.next(); break :blk try self.parseStmt(); } else { break :blk null; } }; const stmt_node = try self.makeNode(.kw_if, if_stmt, else_stmt); // If-statement uses `.kw_if` node for both first node with `expr` on the left // and statements on the right and also `.kw_if` node which goes to the right // and contains both if-branch and else-branch. result = try self.makeNode(.kw_if, expr, stmt_node); }, .left_brace => { try self.next(); while (self.curr.typ != .right_brace and self.curr.typ != .eof) { result = try self.makeNode(.sequence, result, try self.parseStmt()); } try self.expect(.right_brace); }, .identifier => { const identifer = try self.makeLeaf(.identifier, NodeValue.fromToken(self.curr)); try self.next(); try self.expect(.assign); const expr = try self.parseExpr(0); result = try self.makeNode(.assign, identifer, expr); try self.expect(.semicolon); }, .semicolon => try self.next(), else => { std.debug.print("\nSTMT: UNKNOWN {}\n", .{self.curr}); std.os.exit(1); }, } return result; }   /// "Precedence climbing" expression parser. fn parseExpr(self: *Self, precedence: i8) ParserError!?*Tree { var result: ?*Tree = null; switch (self.curr.typ) { .left_paren => { result = try self.parseParenExpr(); }, .subtract => { try self.next(); const metadata = NodeMetadata.find(.negate); const expr = try self.parseExpr(metadata.precedence); result = try self.makeNode(.negate, expr, null); }, .not => { try self.next(); const metadata = NodeMetadata.find(.not); const expr = try self.parseExpr(metadata.precedence); result = try self.makeNode(.not, expr, null); }, .add => { try self.next(); result = try self.parseExpr(precedence); }, .integer, .identifier => { const node_type = NodeMetadata.find(self.curr.typ).node_type; result = try self.makeLeaf(node_type, NodeValue.fromToken(self.curr)); try self.next(); }, else => { std.debug.print("\nEXPR: UNKNOWN {}\n", .{self.curr}); std.os.exit(1); }, }   var curr_metadata = NodeMetadata.find(self.curr.typ); while (curr_metadata.binary and curr_metadata.precedence >= precedence) { const new_precedence = if (curr_metadata.right_associative) curr_metadata.precedence else curr_metadata.precedence + 1; try self.next(); const sub_expr = try self.parseExpr(new_precedence); result = try self.makeNode(curr_metadata.node_type, result, sub_expr); curr_metadata = NodeMetadata.find(self.curr.typ); } return result; }   fn parseParenExpr(self: *Self) ParserError!?*Tree { try self.expect(.left_paren); const result = try self.parseExpr(0); try self.expect(.right_paren); return result; }   fn next(self: *Self) ParserError!void { const token = try self.token_it.next(); if (token) |tok| { self.curr = tok; } else { self.curr = Token{ .line = 0, .col = 0, .typ = .unknown }; } }   fn expect(self: *Self, token_type: TokenType) ParserError!void { if (self.curr.typ != token_type) { const expected_str = NodeMetadata.find(token_type).token_str; const found_str = NodeMetadata.find(self.curr.typ).token_str; std.debug.print( "({d}, {d}) error: Expecting '{s}', found '{s}'\n", .{ self.curr.line, self.curr.col, expected_str, found_str }, ); return ParserError.ExpectedNotFound; } try self.next(); } };   pub fn parse(allocator: std.mem.Allocator, str: []const u8) !?*Tree { var parser = Parser.init(allocator, str); return try parser.parse(); }   pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator();   var arg_it = std.process.args(); _ = try arg_it.next(allocator) orelse unreachable; // program name const file_name = arg_it.next(allocator); // We accept both files and standard input. var file_handle = blk: { if (file_name) |file_name_delimited| { const fname: []const u8 = try file_name_delimited; break :blk try std.fs.cwd().openFile(fname, .{}); } else { break :blk std.io.getStdIn(); } }; defer file_handle.close(); const input_content = try file_handle.readToEndAlloc(allocator, std.math.maxInt(usize));   const result: ?*Tree = try parse(allocator, input_content); const result_str = try astToFlattenedString(allocator, result); _ = try std.io.getStdOut().write(result_str); }   const NodeMetadata = struct { token_type: TokenType, right_associative: bool, binary: bool, unary: bool, precedence: i8, node_type: NodeType, token_str: []const u8,   const self = [_]NodeMetadata{ .{ .token_type = .multiply, .right_associative = false, .binary = true, .unary = false, .precedence = 13, .node_type = .multiply, .token_str = "*" }, .{ .token_type = .divide, .right_associative = false, .binary = true, .unary = false, .precedence = 13, .node_type = .divide, .token_str = "/" }, .{ .token_type = .mod, .right_associative = false, .binary = true, .unary = false, .precedence = 13, .node_type = .mod, .token_str = "%" }, .{ .token_type = .add, .right_associative = false, .binary = true, .unary = false, .precedence = 12, .node_type = .add, .token_str = "+" }, .{ .token_type = .subtract, .right_associative = false, .binary = true, .unary = false, .precedence = 12, .node_type = .subtract, .token_str = "-" }, .{ .token_type = .negate, .right_associative = false, .binary = false, .unary = true, .precedence = 14, .node_type = .negate, .token_str = "-" }, .{ .token_type = .less, .right_associative = false, .binary = true, .unary = false, .precedence = 10, .node_type = .less, .token_str = "<" }, .{ .token_type = .less_equal, .right_associative = false, .binary = true, .unary = false, .precedence = 10, .node_type = .less_equal, .token_str = "<=" }, .{ .token_type = .greater, .right_associative = false, .binary = true, .unary = false, .precedence = 10, .node_type = .greater, .token_str = ">" }, .{ .token_type = .greater_equal, .right_associative = false, .binary = true, .unary = false, .precedence = 10, .node_type = .greater_equal, .token_str = ">=" }, .{ .token_type = .equal, .right_associative = false, .binary = true, .unary = false, .precedence = 9, .node_type = .equal, .token_str = "=" }, .{ .token_type = .not_equal, .right_associative = false, .binary = true, .unary = false, .precedence = 9, .node_type = .not_equal, .token_str = "!=" }, .{ .token_type = .not, .right_associative = false, .binary = false, .unary = true, .precedence = 14, .node_type = .not, .token_str = "!" }, .{ .token_type = .assign, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .assign, .token_str = "=" }, .{ .token_type = .bool_and, .right_associative = false, .binary = true, .unary = false, .precedence = 5, .node_type = .bool_and, .token_str = "&&" }, .{ .token_type = .bool_or, .right_associative = false, .binary = true, .unary = false, .precedence = 4, .node_type = .bool_or, .token_str = "||" }, .{ .token_type = .left_paren, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .unknown, .token_str = "(" }, .{ .token_type = .right_paren, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .unknown, .token_str = ")" }, .{ .token_type = .left_brace, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .unknown, .token_str = "{" }, .{ .token_type = .right_brace, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .unknown, .token_str = "}" }, .{ .token_type = .semicolon, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .unknown, .token_str = ";" }, .{ .token_type = .comma, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .unknown, .token_str = "," }, .{ .token_type = .kw_if, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .kw_if, .token_str = "if" }, .{ .token_type = .kw_else, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .unknown, .token_str = "else" }, .{ .token_type = .kw_while, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .kw_while, .token_str = "while" }, .{ .token_type = .kw_print, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .unknown, .token_str = "print" }, .{ .token_type = .kw_putc, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .unknown, .token_str = "putc" }, .{ .token_type = .identifier, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .identifier, .token_str = "Identifier" }, .{ .token_type = .integer, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .integer, .token_str = "Integer literal" }, .{ .token_type = .string, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .string, .token_str = "String literal" }, .{ .token_type = .eof, .right_associative = false, .binary = false, .unary = false, .precedence = -1, .node_type = .unknown, .token_str = "End of line" }, };   pub fn find(token_type: TokenType) NodeMetadata { for (self) |metadata| { if (metadata.token_type == token_type) return metadata; } else { unreachable; } } };   pub const NodeType = enum { unknown, identifier, string, integer, sequence, kw_if, prtc, prts, prti, kw_while, assign, negate, not, multiply, divide, mod, add, subtract, less, less_equal, greater, greater_equal, equal, not_equal, bool_and, bool_or,   pub fn toString(self: NodeType) []const u8 { return switch (self) { .unknown => "UNKNOWN", .identifier => "Identifier", .string => "String", .integer => "Integer", .sequence => "Sequence", .kw_if => "If", .prtc => "Prtc", .prts => "Prts", .prti => "Prti", .kw_while => "While", .assign => "Assign", .negate => "Negate", .not => "Not", .multiply => "Multiply", .divide => "Divide", .mod => "Mod", .add => "Add", .subtract => "Subtract", .less => "Less", .less_equal => "LessEqual", .greater => "Greater", .greater_equal => "GreaterEqual", .equal => "Equal", .not_equal => "NotEqual", .bool_and => "And", .bool_or => "Or", }; } };   fn astToFlattenedString(allocator: std.mem.Allocator, tree: ?*Tree) ![]const u8 { var result = std.ArrayList(u8).init(allocator); var writer = result.writer(); try treeToString(allocator, writer, tree); return result.items; }   pub const TokenType = enum { unknown, multiply, divide, mod, add, subtract, negate, less, less_equal, greater, greater_equal, equal, not_equal, not, assign, bool_and, bool_or, left_paren, right_paren, left_brace, right_brace, semicolon, comma, kw_if, kw_else, kw_while, kw_print, kw_putc, identifier, integer, string, eof,   const from_string_map = std.ComptimeStringMap(TokenType, .{ .{ "Op_multiply", .multiply }, .{ "Op_divide", .divide }, .{ "Op_mod", .mod }, .{ "Op_add", .add }, .{ "Op_subtract", .subtract }, .{ "Op_negate", .negate }, .{ "Op_less", .less }, .{ "Op_lessequal", .less_equal }, .{ "Op_greater", .greater }, .{ "Op_greaterequal", .greater_equal }, .{ "Op_equal", .equal }, .{ "Op_notequal", .not_equal }, .{ "Op_not", .not }, .{ "Op_assign", .assign }, .{ "Op_and", .bool_and }, .{ "Op_or", .bool_or }, .{ "LeftParen", .left_paren }, .{ "RightParen", .right_paren }, .{ "LeftBrace", .left_brace }, .{ "RightBrace", .right_brace }, .{ "Semicolon", .semicolon }, .{ "Comma", .comma }, .{ "Keyword_if", .kw_if }, .{ "Keyword_else", .kw_else }, .{ "Keyword_while", .kw_while }, .{ "Keyword_print", .kw_print }, .{ "Keyword_putc", .kw_putc }, .{ "Identifier", .identifier }, .{ "Integer", .integer }, .{ "String", .string }, .{ "End_of_input", .eof }, });   pub fn fromString(str: []const u8) TokenType { return from_string_map.get(str).?; } };   pub const TokenValue = union(enum) { integer: i32, string: []const u8, };   pub const Token = struct { line: usize, col: usize, typ: TokenType = .unknown, value: ?TokenValue = null, };   const TreeToStringError = error{OutOfMemory};   fn treeToString( allocator: std.mem.Allocator, writer: std.ArrayList(u8).Writer, tree: ?*Tree, ) TreeToStringError!void { if (tree) |t| { _ = try writer.write(try std.fmt.allocPrint( allocator, "{s}", .{t.typ.toString()}, )); switch (t.typ) { .string, .identifier => _ = try writer.write(try std.fmt.allocPrint( allocator, " {s}\n", .{t.value.?.string}, )), .integer => _ = try writer.write(try std.fmt.allocPrint( allocator, " {d}\n", .{t.value.?.integer}, )), else => { _ = try writer.write(try std.fmt.allocPrint( allocator, "\n", .{}, )); try treeToString(allocator, writer, t.left); try treeToString(allocator, writer, t.right); }, } } else { _ = try writer.write(try std.fmt.allocPrint( allocator, ";\n", .{}, )); } }   pub const LexerOutputTokenizer = struct { it: std.mem.SplitIterator(u8),   const Self = @This();   pub fn init(str: []const u8) Self { return Self{ .it = std.mem.split(u8, str, "\n") }; }   pub fn next(self: *Self) std.fmt.ParseIntError!?Token { if (self.it.next()) |line| { if (line.len == 0) return null; var tokens_it = std.mem.tokenize(u8, line, " "); const lineNumber = try std.fmt.parseInt(usize, tokens_it.next().?, 10); const colNumber = try std.fmt.parseInt(usize, tokens_it.next().?, 10); const typ_text = tokens_it.next().?; const typ = TokenType.fromString(typ_text); const pre_value_index = tokens_it.index; const value = tokens_it.next(); var token = Token{ .line = lineNumber, .col = colNumber, .typ = typ }; if (value) |val| { const token_value = blk: { switch (typ) { .string, .identifier => { tokens_it.index = pre_value_index; break :blk TokenValue{ .string = tokens_it.rest() }; }, .integer => break :blk TokenValue{ .integer = try std.fmt.parseInt(i32, val, 10) }, else => unreachable, } }; token.value = token_value; } return token; } else { return null; } } };   fn stringToTokenList(allocator: std.mem.Allocator, str: []const u8) !std.ArrayList(Token) { var result = std.ArrayList(Token).init(allocator); var lexer_output_it = LexerOutputTokenizer.init(str); while (try lexer_output_it.next()) |token| { try result.append(token); } return result; }  
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.
#Elena
Elena
import extensions; import system'threading; import cellular;   const int maxX = 48; const int maxY = 28;   const int DELAY = 50;   sealed class Model { Space theSpace; RuleSet theRuleSet; bool started;   event Func<Space, object> OnUpdate;   constructor newRandomset(RuleSet transformSet) { theSpace := new IntMatrixSpace.allocate(maxY, maxX, randomSet);   theRuleSet := transformSet;   started := false }   constructor newLoaded(RuleSet initSet, RuleSet transformSet) { theSpace := IntMatrixSpace.allocate(maxY, maxX, initSet);   theRuleSet := transformSet;   started := false }   private onUpdate() { OnUpdate.?(theSpace) }   run() { if (started) { theSpace.update(theRuleSet) } else { started := true };   self.onUpdate() } }   singleton gameOfLifeRuleSet : RuleSet { proceed(Space s, int x, int y, ref int retVal) { int cell := s.at(x, y); int number := s.LiveCell(x, y, 1); // NOTE : number of living cells around the self includes the cell itself   if (cell == 0 && number == 3) { retVal := 1 } else if (cell == 1 && (number == 4 || number == 3)) { retVal := 1 } else { retVal := 0 } } }   public extension presenterOp : Space { print() { console.setCursorPosition(0, 0);   int columns := self.Columns; int rows := self.Rows;   for(int i := 0, i < rows, i += 1) { for(int j := 0, j < columns, j += 1) { int cell := self.at(i, j);   console.write((cell == 0).iif(" ","o")); };   console.writeLine() } } }   public program() { auto model := Model.newRandomset(gameOfLifeRuleSet); console.clear();   model.OnUpdate := (Space sp){ sp.print() };   until (console.KeyAvailable) { model.run();   threadControl.sleep:DELAY };   console.readChar() }
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Standard_ML
Standard ML
datatype tree = Empty | Leaf of int | Node of tree * tree   val t1 = Node (Leaf 1, Node (Leaf 2, Leaf 3))
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Stata
Stata
mata struct Point { real scalar x, y }   // dumb example function test() { struct Point scalar a a.x = 10 a.y = 20 printf("%f\n",a.x+a.y) }   test() 30 end
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Swift
Swift
// Structure struct Point { var x:Int var y:Int }   // Tuple typealias PointTuple = (Int, Int)   // Class class PointClass { var x:Int! var y:Int!   init(x:Int, y:Int) { self.x = x self.y = y } }
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.
#blz
blz
  if i % 2 == 0 print("even") else print("odd") 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
#Forth
Forth
\ linked list of strings creators : ," ( -- ) [CHAR] " WORD c@ 1+ ALLOT  ; \ Parse input stream until " and write into next available memory : [[ ( -- ) 0 C, ; \ begin a list. write a 0 into next memory byte (null string) : ]] ( -- ) [[ ; \ end list with same null string   : nth ( n list -- addr) swap 0 do count + loop ; \ return address of the Nth item in a list   : items ( list -- n ) \ return the number of items in a list 0 >R BEGIN COUNT + DUP R> 1+ >R 0= UNTIL DROP R> 1- ;   : compare$ ( $1 $2 -- -n|0|n ) count rot count compare ; \ compare is an ANS Forth word. returns 0 if $1=$2   : compare[] ( list n1 n2 -- flag) \ compare items n1 and n2 in list ROT dup >R nth ( -- $1) swap r> nth ( -- $1 $2) compare$ ;   \ create our lexical operators : LEX= ( list -- flag) 0 \ place holder for the flag over items 1 DO over I I 1+ compare[] + \ we sum the comparison results on the stack LOOP nip 0= ;   : LEX< ( list -- flag) 0 \ place holder for the flag over items 1 DO over I I 1+ compare[] 0< NOT + LOOP nip 0= ;   \ make some lists create strings [[ ," ENTRY 4" ," ENTRY 3" ," ENTRY 2" ," ENTRY 1" ]] create strings2 [[ ," the same" ," the same" ," the same" ]] create strings3 [[ ," AAA" ," BBB" ," CCC" ," DDD" ]]
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
#Fortran
Fortran
  INTEGER MANY,LONG PARAMETER (LONG = 6,MANY = 4) !Adjust to suit. CHARACTER*(LONG) STRINGS(MANY) !A list of text strings. STRINGS(1) = "Fee" STRINGS(2) = "Fie" STRINGS(3) = "Foe" STRINGS(4) = "Fum" IF (ALL(STRINGS(1:MANY - 1) .LT. STRINGS(2:MANY))) THEN WRITE (6,*) MANY," strings: strictly increasing in order." ELSE WRITE (6,*) MANY," strings: not strictly increasing in order." END IF IF (ALL(STRINGS(1:MANY - 1) .EQ. STRINGS(2:MANY))) THEN WRITE (6,*) MANY," strings: all equal." ELSE WRITE (6,*) MANY," strings: not all equal." END IF END  
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#C
C
#include <stdio.h> #include <string.h> #include <stdlib.h>   char *quib(const char **strs, size_t size) {   size_t len = 3 + ((size > 1) ? (2 * size + 1) : 0); size_t i;   for (i = 0; i < size; i++) len += strlen(strs[i]);   char *s = malloc(len * sizeof(*s)); if (!s) { perror("Can't allocate memory!\n"); exit(EXIT_FAILURE); }   strcpy(s, "{"); switch (size) { case 0: break; case 1: strcat(s, strs[0]); break; default: for (i = 0; i < size - 1; i++) { strcat(s, strs[i]); if (i < size - 2) strcat(s, ", "); else strcat(s, " and "); } strcat(s, strs[i]); break; } strcat(s, "}"); return s; }   int main(void) { const char *test[] = {"ABC", "DEF", "G", "H"}; char *s;   for (size_t i = 0; i < 5; i++) { s = quib(test, i); printf("%s\n", s); free(s); } return EXIT_SUCCESS; }
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
#Clojure
Clojure
  (defn combinations [coll k] (when-let [[x & xs] coll] (if (= k 1) (map list coll) (concat (map (partial cons x) (combinations coll (dec k))) (combinations xs k)))))  
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
#CoffeeScript
CoffeeScript
  combos = (arr, k) -> return [ [] ] if k == 0 return [] if arr.length == 0   combos_with_head = ([arr[0]].concat combo for combo in combos arr, k-1) combos_sans_head = combos arr[1...], k combos_with_head.concat combos_sans_head   arr = ['iced', 'jam', 'plain'] console.log "valid pairs from #{arr.join ','}:" console.log combos arr, 2 console.log "#{combos([1..10], 3).length} ways to order 3 donuts given 10 types"  
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Haskell
Haskell
perm :: Integer -> Integer -> Integer perm n k = product [n-k+1..n]   comb :: Integer -> Integer -> Integer comb n k = perm n k `div` product [1..k]   main :: IO () main = do let showBig maxlen b = let st = show b stlen = length st in if stlen < maxlen then st else take maxlen st ++ "... (" ++ show (stlen-maxlen) ++ " more digits)"   let showPerm pr = putStrLn $ "perm(" ++ show n ++ "," ++ show k ++ ") = " ++ showBig 40 (perm n k) where n = fst pr k = snd pr   let showComb pr = putStrLn $ "comb(" ++ show n ++ "," ++ show k ++ ") = " ++ showBig 40 (comb n k) where n = fst pr k = snd pr   putStrLn "A sample of permutations from 1 to 12:" mapM_ showPerm [(n, n `div` 3) | n <- [1..12] ]   putStrLn "" putStrLn "A sample of combinations from 10 to 60:" mapM_ showComb [(n, n `div` 3) | n <- [10,20..60] ]   putStrLn "" putStrLn "A sample of permutations from 5 to 15000:" mapM_ showPerm [(n, n `div` 3) | n <- [5,50,500,1000,5000,15000] ]   putStrLn "" putStrLn "A sample of combinations from 100 to 1000:" mapM_ showComb [(n, n `div` 3) | n <- [100,200..1000] ]    
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
#Erlang
Erlang
#!/bin/env escript %%%-------------------------------------------------------------------   -record (inp_t, {inpf, pushback, line_no, column_no}).   main (Args) -> main_program (Args).   main_program ([]) -> scan_from_inpf_to_outf ("-", "-"), halt (0); main_program ([Inpf_filename]) -> scan_from_inpf_to_outf (Inpf_filename, "-"), halt (0); main_program ([Inpf_filename, Outf_filename]) -> scan_from_inpf_to_outf (Inpf_filename, Outf_filename), halt (0); main_program ([_, _ | _]) -> ProgName = escript:script_name (), io:put_chars (standard_error, "Usage: "), io:put_chars (standard_error, ProgName), io:put_chars (standard_error, " [INPUTFILE [OUTPUTFILE]]\n"), halt (1).   scan_from_inpf_to_outf ("-", "-") -> scan_input (standard_io, standard_io); scan_from_inpf_to_outf (Inpf_filename, "-") -> case file:open (Inpf_filename, [read]) of {ok, Inpf} -> scan_input (Inpf, standard_io); _ -> open_failure (Inpf_filename, "input") end; scan_from_inpf_to_outf ("-", Outf_filename) -> case file:open (Outf_filename, [write]) of {ok, Outf} -> scan_input (standard_io, Outf); _ -> open_failure (Outf_filename, "output") end; scan_from_inpf_to_outf (Inpf_filename, Outf_filename) -> case file:open(Inpf_filename, [read]) of {ok, Inpf} -> case file:open (Outf_filename, [write]) of {ok, Outf} -> scan_input (Inpf, Outf); _ -> open_failure (Outf_filename, "output") end; _ -> open_failure (Inpf_filename, "input") end.   open_failure (Filename, ForWhat) -> ProgName = escript:script_name (), io:put_chars (standard_error, ProgName), io:put_chars (standard_error, ": failed to open \""), io:put_chars (standard_error, Filename), io:put_chars (standard_error, "\" for "), io:put_chars (standard_error, ForWhat), io:put_chars (standard_error, "\n"), halt (1).   scan_input (Inpf, Outf) -> scan_text (Outf, make_inp (Inpf)).   scan_text (Outf, Inp) -> {TokTup, Inp1} = get_next_token (Inp), print_token (Outf, TokTup), case TokTup of {"End_of_input", _, _, _} -> ok; _ -> scan_text (Outf, Inp1) end.   print_token (Outf, {Tok, Arg, Line_no, Column_no}) -> S_line_no = erlang:integer_to_list (Line_no), S_column_no = erlang:integer_to_list (Column_no), io:put_chars (Outf, string:pad (S_line_no, 5, leading)), io:put_chars (Outf, " "), io:put_chars (Outf, string:pad (S_column_no, 5, leading)), io:put_chars (Outf, " "), io:put_chars (Outf, Tok), {Padding, Arg1} = case Tok of "Identifier" -> {" ", Arg}; "Integer" -> {" ", Arg}; "String" -> {" ", Arg}; _ -> {"", ""} end, io:put_chars (Outf, Padding), io:put_chars (Outf, Arg1), io:put_chars ("\n").   %%%------------------------------------------------------------------- %%% %%% The token dispatcher. %%%   get_next_token (Inp) -> Inp00 = skip_spaces_and_comments (Inp), {Ch, Inp0} = get_ch (Inp00), {Char, Line_no, Column_no} = Ch, Ln = Line_no, Cn = Column_no, case Char of eof -> {{"End_of_input", "", Ln, Cn}, Inp0}; "," -> {{"Comma", ",", Ln, Cn}, Inp0}; ";" -> {{"Semicolon", ";", Ln, Cn}, Inp0}; "(" -> {{"LeftParen", "(", Ln, Cn}, Inp0}; ")" -> {{"RightParen", ")", Ln, Cn}, Inp0}; "{" -> {{"LeftBrace", "{", Ln, Cn}, Inp0}; "}" -> {{"RightBrace", "}", Ln, Cn}, Inp0}; "*" -> {{"Op_multiply", "*", Ln, Cn}, Inp0}; "/" -> {{"Op_divide", "/", Ln, Cn}, Inp0}; "%" -> {{"Op_mod", "%", Ln, Cn}, Inp0}; "+" -> {{"Op_add", "+", Ln, Cn}, Inp0}; "-" -> {{"Op_subtract", "-", Ln, Cn}, Inp0}; "<" -> {Ch1, Inp1} = get_ch (Inp0), {Char1, _, _} = Ch1, case Char1 of "=" -> {{"Op_lessequal", "<=", Ln, Cn}, Inp1}; _ -> {{"Op_less", "<", Ln, Cn}, push_back (Ch1, Inp1)} end; ">" -> {Ch1, Inp1} = get_ch (Inp0), {Char1, _, _} = Ch1, case Char1 of "=" -> {{"Op_greaterequal", ">=", Ln, Cn}, Inp1}; _ -> {{"Op_greater", ">", Ln, Cn}, push_back (Ch1, Inp1)} end; "=" -> {Ch1, Inp1} = get_ch (Inp0), {Char1, _, _} = Ch1, case Char1 of "=" -> {{"Op_equal", "==", Ln, Cn}, Inp1}; _ -> {{"Op_assign", "=", Ln, Cn}, push_back (Ch1, Inp1)} end; "!" -> {Ch1, Inp1} = get_ch (Inp0), {Char1, _, _} = Ch1, case Char1 of "=" -> {{"Op_notequal", "!=", Ln, Cn}, Inp1}; _ -> {{"Op_not", "!", Ln, Cn}, push_back (Ch1, Inp1)} end; "&" -> {Ch1, Inp1} = get_ch (Inp0), {Char1, _, _} = Ch1, case Char1 of "&" -> {{"Op_and", "&&", Ln, Cn}, Inp1}; _ -> unexpected_character (Ln, Cn, Char) end; "|" -> {Ch1, Inp1} = get_ch (Inp0), {Char1, _, _} = Ch1, case Char1 of "|" -> {{"Op_or", "||", Ln, Cn}, Inp1}; _ -> unexpected_character (Ln, Cn, Char) end; "\"" -> Inp1 = push_back (Ch, Inp0), scan_string_literal (Inp1); "'" -> Inp1 = push_back (Ch, Inp0), scan_character_literal (Inp1); _ -> case is_digit (Char) of true -> Inp1 = push_back (Ch, Inp0), scan_integer_literal (Inp1); false -> case is_alpha_or_underscore (Char) of true -> Inp1 = push_back (Ch, Inp0), scan_identifier_or_reserved_word (Inp1); false -> unexpected_character (Ln, Cn, Char) end end end.   %%%------------------------------------------------------------------- %%% %%% Skipping past spaces and /* ... */ comments. %%% %%% Comments are treated exactly like a bit of whitespace. They never %%% make it to the dispatcher. %%%   skip_spaces_and_comments (Inp) -> {Ch, Inp0} = get_ch (Inp), {Char, Line_no, Column_no} = Ch, case classify_char (Char) of eof -> push_back (Ch, Inp0); space -> skip_spaces_and_comments (Inp0); slash -> {Ch1, Inp1} = get_ch (Inp0), case Ch1 of {"*", _, _} -> Inp2 = scan_comment (Inp1, Line_no, Column_no), skip_spaces_and_comments (Inp2); _ -> push_back (Ch, (push_back (Ch1, Inp1))) end; other -> push_back (Ch, Inp0) end.   classify_char (Char) -> case Char of eof -> eof; "/" -> slash; _ -> case is_space (Char) of true -> space; false -> other end end.   scan_comment (Inp, Line_no, Column_no) -> {Ch0, Inp0} = get_ch (Inp), case Ch0 of {eof, _, _} -> unterminated_comment (Line_no, Column_no); {"*", _, _} -> {Ch1, Inp1} = get_ch (Inp0), case Ch1 of {eof, _, _} -> unterminated_comment (Line_no, Column_no); {"/", _, _} -> Inp1; _ -> scan_comment (Inp1, Line_no, Column_no) end; _ -> scan_comment (Inp0, Line_no, Column_no) end.   is_space (S) -> case re:run (S, "^[[:space:]]+$") of {match, _} -> true; _ -> false end.   %%%------------------------------------------------------------------- %%% %%% Scanning of integer literals, identifiers, and reserved words. %%% %%% These three types of token are very similar to each other. %%%   scan_integer_literal (Inp) -> %% Scan an entire word, not just digits. This way we detect %% erroneous text such as "23skidoo". {Line_no, Column_no, Inp1} = get_position (Inp), {Word, Inp2} = scan_word (Inp1), case is_digit (Word) of true -> {{"Integer", Word, Line_no, Column_no}, Inp2}; false -> invalid_integer_literal (Line_no, Column_no, Word) end.   scan_identifier_or_reserved_word (Inp) -> %% It is assumed that the first character is of the correct type, %% thanks to the dispatcher. {Line_no, Column_no, Inp1} = get_position (Inp), {Word, Inp2} = scan_word (Inp1), Tok = case Word of "if" -> "Keyword_if"; "else" -> "Keyword_else"; "while" -> "Keyword_while"; "print" -> "Keyword_print"; "putc" -> "Keyword_putc"; _ -> "Identifier" end, {{Tok, Word, Line_no, Column_no}, Inp2}.   scan_word (Inp) -> scan_word_loop (Inp, "").   scan_word_loop (Inp, Word0) -> {Ch1, Inp1} = get_ch (Inp), {Char1, _, _} = Ch1, case is_alnum_or_underscore (Char1) of true -> scan_word_loop (Inp1, Word0 ++ Char1); false -> {Word0, push_back (Ch1, Inp1)} end.   get_position (Inp) -> {Ch1, Inp1} = get_ch (Inp), {_, Line_no, Column_no} = Ch1, Inp2 = push_back (Ch1, Inp1), {Line_no, Column_no, Inp2}.   is_digit (S) -> case re:run (S, "^[[:digit:]]+$") of {match, _} -> true; _ -> false end.   is_alpha_or_underscore (S) -> case re:run (S, "^[[:alpha:]_]+$") of {match, _} -> true; _ -> false end.   is_alnum_or_underscore (S) -> case re:run (S, "^[[:alnum:]_]+$") of {match, _} -> true; _ -> false end.   %%%------------------------------------------------------------------- %%% %%% Scanning of string literals. %%% %%% It is assumed that the first character is the opening quote, and %%% that the closing quote is the same character. %%%     scan_string_literal (Inp) -> {Ch1, Inp1} = get_ch (Inp), {Quote_mark, Line_no, Column_no} = Ch1, {Contents, Inp2} = scan_str_lit (Inp1, Ch1), Toktup = {"String", Quote_mark ++ Contents ++ Quote_mark, Line_no, Column_no}, {Toktup, Inp2}.   scan_str_lit (Inp, Ch) -> scan_str_lit_loop (Inp, Ch, "").   scan_str_lit_loop (Inp, Ch, Contents) -> {Quote_mark, Line_no, Column_no} = Ch, {Ch1, Inp1} = get_ch (Inp), {Char1, Line_no1, Column_no1} = Ch1, case Char1 of Quote_mark -> {Contents, Inp1}; eof -> eoi_in_string_literal (Line_no, Column_no); "\n" -> eoln_in_string_literal (Line_no, Column_no); "\\" -> {Ch2, Inp2} = get_ch (Inp1), {Char2, _, _} = Ch2, case Char2 of "n" -> scan_str_lit_loop (Inp2, Ch, Contents ++ "\\n"); "\\" -> scan_str_lit_loop (Inp2, Ch, Contents ++ "\\\\"); _ -> unsupported_escape (Line_no1, Column_no1, Char2) end; _ -> scan_str_lit_loop (Inp1, Ch, Contents ++ Char1) end.   %%%------------------------------------------------------------------- %%% %%% Scanning of character literals. %%% %%% It is assumed that the first character is the opening quote, and %%% that the closing quote is the same character. %%% %%% The tedious part of scanning a character literal is distinguishing %%% between the kinds of lexical error. (One might wish to modify the %%% code to detect, as a distinct kind of error, end of line within a %%% character literal.) %%%   scan_character_literal (Inp) -> {Ch, Inp0} = get_ch (Inp), {_, Line_no, Column_no} = Ch, {Ch1, Inp1} = get_ch (Inp0), {Char1, Line_no1, Column_no1} = Ch1, {Intval, Inp3} = case Char1 of eof -> unterminated_character_literal (Line_no, Column_no); "\\" -> {Ch2, Inp2} = get_ch (Inp1), {Char2, _, _} = Ch2, case Char2 of eof -> unterminated_character_literal (Line_no, Column_no); "n" -> {char_to_code ("\n"), Inp2}; "\\" -> {char_to_code ("\\"), Inp2}; _ -> unsupported_escape (Line_no1, Column_no1, Char2) end; _ -> {char_to_code (Char1), Inp1} end, Inp4 = check_character_literal_end (Inp3, Ch), {{"Integer", Intval, Line_no, Column_no}, Inp4}.   char_to_code (Char) -> %% Hat tip to https://archive.ph/BxZRS lists:flatmap (fun erlang:integer_to_list/1, Char).   check_character_literal_end (Inp, Ch) -> {Char, _, _} = Ch, {{Char1, _, _}, Inp1} = get_ch (Inp), case Char1 of Char -> Inp1; _ -> find_char_lit_end (Inp1, Ch) % Handle a lexical error. end.   find_char_lit_end (Inp, Ch) -> %% There is a lexical error. Determine which kind it fits into. {Char, Line_no, Column_no} = Ch, {{Char1, _, _}, Inp1} = get_ch (Inp), case Char1 of Char -> multicharacter_literal (Line_no, Column_no); eof -> unterminated_character_literal (Line_no, Column_no); _ -> find_char_lit_end (Inp1, Ch) end.   %%%------------------------------------------------------------------- %%% %%% Character-at-a-time input, with unrestricted pushback, and with %%% line and column numbering. %%%   make_inp (Inpf) -> #inp_t{inpf = Inpf, pushback = [], line_no = 1, column_no = 1}.   get_ch (Inp) -> #inp_t{inpf = Inpf, pushback = Pushback, line_no = Line_no, column_no = Column_no} = Inp, case Pushback of [Ch | Tail] -> Inp1 = Inp#inp_t{pushback = Tail}, {Ch, Inp1}; [] -> case io:get_chars (Inpf, "", 1) of eof -> Ch = {eof, Line_no, Column_no}, {Ch, Inp}; {error, _} -> Ch = {eof, Line_no, Column_no}, {Ch, Inp}; Char -> case Char of "\n" -> Ch = {Char, Line_no, Column_no}, Inp1 = Inp#inp_t{line_no = Line_no + 1, column_no = 1}, {Ch, Inp1}; _ -> Ch = {Char, Line_no, Column_no}, Inp1 = Inp#inp_t{column_no = Column_no + 1}, {Ch, Inp1} end end end.   push_back (Ch, Inp) -> Inp#inp_t{pushback = [Ch | Inp#inp_t.pushback]}.   %%%-------------------------------------------------------------------   invalid_integer_literal (Line_no, Column_no, Word) -> error_abort ("invalid integer literal \"" ++ Word ++ "\" at " ++ integer_to_list (Line_no) ++ ":" ++ integer_to_list (Column_no)).   unsupported_escape (Line_no, Column_no, Char) -> error_abort ("unsupported escape \\" ++ Char ++ " at " ++ integer_to_list (Line_no) ++ ":" ++ integer_to_list (Column_no)).   unexpected_character (Line_no, Column_no, Char) -> error_abort ("unexpected character '" ++ Char ++ "' at " ++ integer_to_list (Line_no) ++ ":" ++ integer_to_list (Column_no)).   eoi_in_string_literal (Line_no, Column_no) -> error_abort ("end of input in string literal starting at " ++ integer_to_list (Line_no) ++ ":" ++ integer_to_list (Column_no)).   eoln_in_string_literal (Line_no, Column_no) -> error_abort ("end of line in string literal starting at " ++ integer_to_list (Line_no) ++ ":" ++ integer_to_list (Column_no)).   unterminated_character_literal (Line_no, Column_no) -> error_abort ("unterminated character literal starting at " ++ integer_to_list (Line_no) ++ ":" ++ integer_to_list (Column_no)).   multicharacter_literal (Line_no, Column_no) -> error_abort ("unsupported multicharacter literal starting at " ++ integer_to_list (Line_no) ++ ":" ++ integer_to_list (Column_no)).   unterminated_comment (Line_no, Column_no) -> error_abort ("unterminated comment starting at " ++ integer_to_list (Line_no) ++ ":" ++ integer_to_list (Column_no)).   error_abort (Message) -> ProgName = escript:script_name (), io:put_chars (standard_error, ProgName), io:put_chars (standard_error, ": "), io:put_chars (standard_error, Message), io:put_chars (standard_error, "\n"), halt (1).   %%%------------------------------------------------------------------- %%% Instructions to GNU Emacs -- %%% local variables: %%% mode: erlang %%% erlang-indent-level: 3 %%% 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"
#Common_Lisp
Common Lisp
(defun argv () (or #+clisp (ext:argv) #+sbcl sb-ext:*posix-argv* #+abcl ext:*command-line-argument-list* #+clozure (ccl::command-line-arguments) #+gcl si:*command-args* #+ecl (loop for i from 0 below (si:argc) collect (si:argv i)) #+cmu extensions:*command-line-strings* #+allegro (sys:command-line-arguments) #+lispworks sys:*line-arguments-list* nil))
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"
#Cowgol
Cowgol
include "cowgol.coh"; include "argv.coh";   ArgvInit(); var i: uint8 := 0;   loop var arg := ArgvNext(); if arg == 0 as [uint8] then break; end if; i := i + 1; print_i8(i); print(": '"); print(arg); print("'\n"); end loop;
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.)
#AutoIt
AutoIt
  #cs Everything between the cs and and the ce is commented. Commented code is not used by the computer. #ce ;individual lines after a semicolon are commented.  
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.)
#AWK
AWK
BEGIN { # this code does something # do something }
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#Racket
Racket
#lang typed/racket ;;; ;;; The Rosetta Code Virtual Machine, in Typed Racket. ;;; ;;; Migrated from the Common Lisp. ;;;   ;;; Yes, I could compute how much memory is needed, or I could assume ;;; that the instructions are in address order. However, for *this* ;;; implementation I am going to use a large fixed-size memory and use ;;; the address fields of instructions to place the instructions. (: executable-memory-size Positive-Fixnum) (define executable-memory-size 65536)   ;;; Similarly, I am going to have fixed size data and stack memory. (: data-memory-size Positive-Fixnum) (define data-memory-size 2048) (: stack-memory-size Positive-Fixnum) (define stack-memory-size 2048)   ;;; And so I am going to have specialized types for the different ;;; kinds of memory the platform contains. Also for its "word" and ;;; register types. (define-type Word Nonnegative-Fixnum) (define-type Register (Boxof Word)) (define-type Executable-Memory (Mutable-Vectorof Byte)) (define-type Data-Memory (Mutable-Vectorof Word)) (define-type Stack-Memory (Mutable-Vectorof Word))   (define re-blank-line #px"^\\s*$") (define re-parse-instr-1 #px"^\\s*(\\d+)\\s*(.*\\S)") (define re-parse-instr-2 #px"(?i:^(\\S+)\\s*(.*))") (define re-parse-instr-3 #px"^[[(]?([0-9-]+)") (define re-header #px"(?i:^\\s*Datasize\\s*:\\s*(\\d+)\\s*Strings\\s*:\\s*(\\d+))") (define re-leading-spaces #px"^\\s*")   (define opcode-names '("halt" "add" "sub" "mul" "div" "mod" "lt" "gt" "le" "ge" "eq" "ne" "and" "or" "neg" "not" "prtc" "prti" "prts" "fetch" "store" "push" "jmp" "jz"))   (: blank-line? (String -> Boolean)) (define (blank-line? s) (not (not (regexp-match re-blank-line s))))   (: opcode-from-name (String -> Byte)) (define (opcode-from-name s) (let ((i (index-of opcode-names s))) (assert i) (cast i Byte)))   (: create-executable-memory (-> Executable-Memory)) (define (create-executable-memory) (make-vector executable-memory-size (opcode-from-name "halt")))   (: create-data-memory (-> Data-Memory)) (define (create-data-memory) (make-vector data-memory-size 0))   (: create-stack-memory (-> Stack-Memory)) (define (create-stack-memory) (make-vector stack-memory-size 0))   (: create-register (-> Register)) (define (create-register) (box 0))   (struct machine ((sp : Register)  ; Stack pointer. (ip : Register)  ; Instruction pointer (that is, program counter). (code : Executable-Memory) (data : Data-Memory) (stack : Stack-Memory) (strings : (Immutable-Vectorof String)) (output : Output-Port)) #:type-name Machine #:constructor-name %make-machine)   (: make-machine ((Immutable-Vectorof String) Output-Port -> Machine)) (define (make-machine strings outf) (%make-machine (create-register) (create-register) (create-executable-memory) (create-data-memory) (create-stack-memory) strings outf))   (define-type Instruction-Data (List Word Byte (U False Word)))   (: insert-instruction (Executable-Memory Instruction-Data -> Void)) (define (insert-instruction memory instr) (void (match instr ((list address opcode arg) (let ((instr-size (if arg 5 1))) (unless (<= (+ address instr-size) executable-memory-size) (raise-user-error "the VM's executable memory size is exceeded")) (vector-set! memory address opcode) (when arg  ;; Big-endian order. (vector-set! memory (+ address 1) (bitwise-and (arithmetic-shift arg -24) #xFF)) (vector-set! memory (+ address 2) (bitwise-and (arithmetic-shift arg -16) #xFF)) (vector-set! memory (+ address 3) (bitwise-and (arithmetic-shift arg -8) #xFF)) (vector-set! memory (+ address 4) (bitwise-and arg #xFF))))))))   (: load-executable-memory (Executable-Memory (Listof Instruction-Data) -> Void)) (define (load-executable-memory memory instr-lst) (let loop ((p instr-lst)) (if (null? p) (void) (let ((instr (car p))) (insert-instruction memory (car p)) (loop (cdr p))))))   (: number->word (Number -> Word)) (define (number->word n) (cast (bitwise-and (cast n Integer) #xFFFFFFFF) Word))   (: string->word (String -> Word)) (define (string->word s) (let ((n (string->number s))) (assert (number? n)) (number->word n)))   (: parse-instruction (String -> (U False Instruction-Data))) (define (parse-instruction s) (and (not (blank-line? s)) (let* ((strings (cast (regexp-match re-parse-instr-1 s) (Listof String))) (address (cast (string->number (second strings)) Word)) (split (cast (regexp-match re-parse-instr-2 (third strings)) (Listof String))) (opcode-name (string-downcase (second split))) (opcode (opcode-from-name opcode-name)) (arguments (third split)) (has-arg? (match opcode-name ((or "fetch" "store" "push" "jmp" "jz") #t) (_ #f)))) (if has-arg? (let* ((argstr-lst (cast (regexp-match re-parse-instr-3 arguments) (Listof String))) (argstr (second argstr-lst)) (arg (string->word argstr))) `(,address ,opcode ,arg)) `(,address ,opcode #f)))))   (: read-instructions (Input-Port -> (Listof Instruction-Data))) (define (read-instructions inpf) (let loop ((line (read-line inpf)) (lst (cast '() (Listof Instruction-Data)))) (if (eof-object? line) (reverse lst) (let ((instr (parse-instruction line))) (loop (read-line inpf) (if instr (cons instr lst) lst))))))   (: read-datasize-and-strings-count (Input-Port -> (Values Word Word))) (define (read-datasize-and-strings-count inpf) (let ((line (read-line inpf))) (unless (string? line) (raise-user-error "empty input"))  ;; This is a permissive implementation. (let* ((strings (cast (regexp-match re-header line) (Listof String))) (datasize (string->word (second strings))) (strings-count (string->word (third strings)))) (values datasize strings-count))))   (: parse-string-literal (String -> String)) (define (parse-string-literal s)  ;; This is a permissive implementation, but only in that it skips  ;; any leading space. It does not check carefully for outright  ;; mistakes. (let* ((s (regexp-replace re-leading-spaces s "")) (quote-mark (string-ref s 0))) (let loop ((i 1) (lst (cast '() (Listof Char)))) (if (char=? (string-ref s i) quote-mark) (list->string (reverse lst)) (let ((c (string-ref s i))) (if (char=? c #\\) (let ((c0 (match (string-ref s (+ i 1)) (#\n #\newline) (c1 c1)))) (loop (+ i 2) (cons c0 lst))) (loop (+ i 1) (cons c lst))))))))   (: read-string-literals (Input-Port Word -> (Listof String))) (define (read-string-literals inpf strings-count) (for/list ((i (in-range strings-count))) (let ((line (read-line inpf))) (begin (assert (string? line)) (parse-string-literal line)))))   (: open-inpf (String -> Input-Port)) (define (open-inpf inpf-filename) (if (string=? inpf-filename "-") (current-input-port) (open-input-file inpf-filename)))   (: open-outf (String -> Output-Port)) (define (open-outf outf-filename) (if (string=? outf-filename "-") (current-output-port) (open-output-file outf-filename #:exists 'truncate)))   (: word-signbit? (Word -> Boolean)) (define (word-signbit? x)  ;; True if and only if the sign bit is set. (not (zero? (bitwise-and x #x80000000))))   (: word-add (Word Word -> Word)) (define (word-add x y)  ;; Addition with overflow freely allowed. (cast (bitwise-and (+ x y) #xFFFFFFFF) Word))   (: word-neg (Word -> Word)) (define (word-neg x)  ;; The two's complement. (word-add (cast (bitwise-xor x #xFFFFFFFF) Word) 1))   (: word-sub (Word Word -> Word)) (define (word-sub x y)  ;; Subtraction with overflow freely allowed. (word-add x (word-neg y)))   (: word-mul (Word Word -> Word)) (define (word-mul x y)  ;; Signed multiplication. (let ((x<0 (word-signbit? x)) (y<0 (word-signbit? y))) (let ((abs-x (if x<0 (word-neg x) x)) (abs-y (if y<0 (word-neg y) y))) (let* ((abs-xy (cast (bitwise-and (* abs-x abs-y) #xFFFFFFFF) Word))) (if x<0 (if y<0 abs-xy (word-neg abs-xy)) (if y<0 (word-neg abs-xy) abs-xy))))))   (: word-div (Word Word -> Word)) (define (word-div x y)  ;; The quotient after signed integer division with truncation  ;; towards zero. (let ((x<0 (word-signbit? x)) (y<0 (word-signbit? y))) (let ((abs-x (if x<0 (word-neg x) x)) (abs-y (if y<0 (word-neg y) y))) (let* ((abs-x/y (cast (bitwise-and (quotient abs-x abs-y) #xFFFFFFFF) Word))) (if x<0 (if y<0 abs-x/y (word-neg abs-x/y)) (if y<0 (word-neg abs-x/y) abs-x/y))))))   (: word-mod (Word Word -> Word)) (define (word-mod x y)  ;; The remainder after signed integer division with truncation  ;; towards zero. (let ((x<0 (word-signbit? x)) (y<0 (word-signbit? y))) (let ((abs-x (if x<0 (word-neg x) x)) (abs-y (if y<0 (word-neg y) y))) (let* ((abs-x/y (cast (bitwise-and (remainder abs-x abs-y) #xFFFFFFFF) Word))) (if x<0 (if y<0 abs-x/y (word-neg abs-x/y)) (if y<0 (word-neg abs-x/y) abs-x/y))))))   (: b2i (Boolean -> (U Zero One))) (define (b2i b) (if b 1 0))   (: word-lt (Word Word -> Word)) (define (word-lt x y)  ;; Signed comparison: is x less than y? (let ((x<0 (word-signbit? x)) (y<0 (word-signbit? y))) (b2i (if x<0 (if y<0 (< x y) #t) (if y<0 #f (< x y))))))   (: word-le (Word Word -> Word)) (define (word-le x y)  ;; Signed comparison: is x less than or equal to y? (let ((x<0 (word-signbit? x)) (y<0 (word-signbit? y))) (b2i (if x<0 (if y<0 (<= x y) #t) (if y<0 #f (<= x y))))))   (: word-gt (Word Word -> Word)) (define (word-gt x y)  ;; Signed comparison: is x greater than y? (let ((x<0 (word-signbit? x)) (y<0 (word-signbit? y))) (b2i (if x<0 (if y<0 (> x y) #f) (if y<0 #t (> x y))))))   (: word-ge (Word Word -> Word)) (define (word-ge x y)  ;; Signed comparison: is x greater than or equal to y? (let ((x<0 (word-signbit? x)) (y<0 (word-signbit? y))) (b2i (if x<0 (if y<0 (>= x y) #f) (if y<0 #t (>= x y))))))   (: word-eq (Word Word -> Word)) (define (word-eq x y)  ;; Is x equal to y? (b2i (= x y)))   (: word-ne (Word Word -> Word)) (define (word-ne x y)  ;; Is x not equal to y? (b2i (not (= x y))))   (: word-cmp (Word -> Word)) (define (word-cmp x)  ;; The logical complement. (b2i (zero? x)))   (: word-and (Word Word -> Word)) (define (word-and x y)  ;; The logical conjunction. (b2i (and (not (zero? x)) (not (zero? y)))))   (: word-or (Word Word -> Word)) (define (word-or x y)  ;; The logical disjunction. (b2i (or (not (zero? x)) (not (zero? y)))))   (: unop (Stack-Memory Register (Word -> Word) -> Void)) (define (unop stack sp operation)  ;; Perform a unary operation on the stack. (let ((i (unbox sp))) (unless (<= 1 i) (raise-user-error "stack underflow")) (let ((x (vector-ref stack (- i 1))))  ;; Note how, in contrast to Common Lisp, "operation" is not in a  ;; namespace separate from that of "ordinary" values, such as  ;; numbers and strings. (Which way is "better" is a matter of  ;; taste, and probably depends mostly on what "functional"  ;; language one learnt first. Mine was Caml Light, so I prefer  ;; the Scheme way. :) ) (vector-set! stack (- i 1) (operation x)))))   (: binop (Stack-Memory Register (Word Word -> Word) -> Void)) (define (binop stack sp operation)  ;; Perform a binary operation on the stack. (let ((i (unbox sp))) (unless (<= 2 i) (raise-user-error "stack underflow")) (let ((x (vector-ref stack (- i 2))) (y (vector-ref stack (- i 1)))) (vector-set! stack (- i 2) (operation x y))) (set-box! sp (cast (- i 1) Word))))   (: jri (Executable-Memory Register -> Void)) (define (jri code ip)  ;; Jump relative immediate. (let ((j (unbox ip))) (unless (<= (+ j 4) executable-memory-size) (raise-user-error "address past end of executable memory"))  ;; Big-endian order. (let* ((offset (vector-ref code (+ j 3))) (offset (bitwise-ior (arithmetic-shift (vector-ref code (+ j 2)) 8) offset)) (offset (bitwise-ior (arithmetic-shift (vector-ref code (+ j 1)) 16) offset)) (offset (bitwise-ior (arithmetic-shift (vector-ref code j) 24) offset))) (set-box! ip (word-add j (cast offset Word))))))   (: jriz (Stack-Memory Register Executable-Memory Register -> Void)) (define (jriz stack sp code ip)  ;; Jump relative immediate, if zero. (let ((i (unbox sp))) (unless (<= 1 i) (raise-user-error "stack underflow")) (let ((x (vector-ref stack (- i 1)))) (set-box! sp (- i 1)) (if (zero? x) (jri code ip) (let ((j (unbox ip))) (set-box! ip (cast (+ j 4) Word)))))))   (: get-immediate-value (Executable-Memory Register -> Word)) (define (get-immediate-value code ip) (let ((j (unbox ip))) (unless (<= (+ j 4) executable-memory-size) (raise-user-error "address past end of executable memory"))  ;; Big-endian order. (let* ((x (vector-ref code (+ j 3))) (x (bitwise-ior (arithmetic-shift (vector-ref code (+ j 2)) 8) x)) (x (bitwise-ior (arithmetic-shift (vector-ref code (+ j 1)) 16) x)) (x (bitwise-ior (arithmetic-shift (vector-ref code j) 24) x))) (set-box! ip (cast (+ j 4) Word)) (cast x Word))))   (: pushi (Stack-Memory Register Executable-Memory Register -> Void)) (define (pushi stack sp code ip)  ;; Push-immediate a value from executable memory onto the stack. (let ((i (unbox sp))) (unless (< i stack-memory-size) (raise-user-error "stack overflow")) (vector-set! stack i (get-immediate-value code ip)) (set-box! sp (cast (+ i 1) Word))))   (: fetch (Stack-Memory Register Executable-Memory Register Data-Memory -> Void)) (define (fetch stack sp code ip data)  ;; Fetch data to the stack, using the storage location given in  ;; executable memory. (let ((i (unbox sp))) (unless (< i stack-memory-size) (raise-user-error "stack overflow")) (let* ((k (get-immediate-value code ip)) (x (vector-ref data k))) (vector-set! stack i x) (set-box! sp (cast (+ i 1) Word)))))   (: pop-one (Stack-Memory Register -> Word)) (define (pop-one stack sp) (let ((i (unbox sp))) (unless (<= 1 i) (raise-user-error "stack underflow")) (let* ((x (vector-ref stack (- i 1)))) (set-box! sp (- i 1)) x)))   (: store (Stack-Memory Register Executable-Memory Register Data-Memory -> Void)) (define (store stack sp code ip data)  ;; Store data from the stack, using the storage location given in  ;; executable memory. (let ((i (unbox sp))) (unless (<= 1 i) (raise-user-error "stack underflow")) (let ((k (get-immediate-value code ip)) (x (pop-one stack sp))) (vector-set! data k x))))   (: prti (Stack-Memory Register Output-Port -> Void)) (define (prti stack sp outf)  ;; Print the top value of the stack, as a signed decimal value. (let* ((n (pop-one stack sp)) (n<0 (word-signbit? n))) (if n<0 (begin (display "-" outf) (display (word-neg n) outf)) (display n outf))))   (: prtc (Stack-Memory Register Output-Port -> Void)) (define (prtc stack sp outf)  ;; Print the top value of the stack, as a character. (let ((c (pop-one stack sp))) (display (integer->char c) outf)))   (: prts (Stack-Memory Register (Immutable-Vectorof String) Output-Port -> Void)) (define (prts stack sp strings outf)  ;; Print the string specified by the top of the stack. (let* ((k (pop-one stack sp)) (s (vector-ref strings k))) (display s outf)))   ;; ;; I have written macros in the standard R6RS fashion, with a lambda ;; and syntax-case, so the examples may be widely illustrative. Racket ;; supports this style, despite (purposely) not adhering to any Scheme ;; standard. ;; ;; Some Schemes that do not provide syntax-case (CHICKEN, for ;; instance) provide alternatives that may be quite different. ;; ;; R5RS and R7RS require only syntax-rules, which cannot do what we ;; are doing here. (What we are doing is similar to using ## in a ;; modern C macro, except that the pieces are not merely raw text, and ;; they must be properly typed at every stage.) ;; (define-syntax define-machine-binop (lambda (stx) (syntax-case stx () ((_ op) (let* ((op^ (syntax->datum #'op)) (machine-op (string-append "machine-" op^)) (machine-op (string->symbol machine-op)) (machine-op (datum->syntax stx machine-op)) (word-op (string-append "word-" op^)) (word-op (string->symbol word-op)) (word-op (datum->syntax stx word-op))) #`(begin (: #,machine-op (Machine -> Void)) (define (#,machine-op mach) (binop (machine-stack mach) (machine-sp mach) #,word-op))))))))   (define-syntax define-machine-unop (lambda (stx) (syntax-case stx () ((_ op) (let* ((op^ (syntax->datum #'op)) (machine-op (string-append "machine-" op^)) (machine-op (string->symbol machine-op)) (machine-op (datum->syntax stx machine-op)) (word-op (string-append "word-" op^)) (word-op (string->symbol word-op)) (word-op (datum->syntax stx word-op))) #`(begin (: #,machine-op (Machine -> Void)) (define (#,machine-op mach) (unop (machine-stack mach) (machine-sp mach) #,word-op))))))))   (define-machine-binop "add") (define-machine-binop "sub") (define-machine-binop "mul") (define-machine-binop "div") (define-machine-binop "mod") (define-machine-binop "lt") (define-machine-binop "gt") (define-machine-binop "le") (define-machine-binop "ge") (define-machine-binop "eq") (define-machine-binop "ne") (define-machine-binop "and") (define-machine-binop "or")   (define-machine-unop "neg")   (: machine-not (Machine -> Void)) (define (machine-not mach) (unop (machine-stack mach) (machine-sp mach) word-cmp))   (: machine-prtc (Machine -> Void)) (define (machine-prtc mach) (prtc (machine-stack mach) (machine-sp mach) (machine-output mach)))   (: machine-prti (Machine -> Void)) (define (machine-prti mach) (prti (machine-stack mach) (machine-sp mach) (machine-output mach)))   (: machine-prts (Machine -> Void)) (define (machine-prts mach) (prts (machine-stack mach) (machine-sp mach) (machine-strings mach) (machine-output mach)))   (: machine-fetch (Machine -> Void)) (define (machine-fetch mach) (fetch (machine-stack mach) (machine-sp mach) (machine-code mach) (machine-ip mach) (machine-data mach)))   (: machine-store (Machine -> Void)) (define (machine-store mach) (store (machine-stack mach) (machine-sp mach) (machine-code mach) (machine-ip mach) (machine-data mach)))   (: machine-push (Machine -> Void)) (define (machine-push mach) (pushi (machine-stack mach) (machine-sp mach) (machine-code mach) (machine-ip mach)))   (: machine-jmp (Machine -> Void)) (define (machine-jmp mach) (jri (machine-code mach) (machine-ip mach)))   (: machine-jz (Machine -> Void)) (define (machine-jz mach) (jriz (machine-stack mach) (machine-sp mach) (machine-code mach) (machine-ip mach)))   (: get-opcode (Machine -> Byte)) (define (get-opcode mach) (let ((code (machine-code mach)) (ip (machine-ip mach))) (let ((j (unbox ip))) (unless (< j executable-memory-size) (raise-user-error "address past end of executable memory")) (let ((opcode (vector-ref code j))) (set-box! ip (cast (+ j 1) Word)) opcode))))   (: run-instruction (Machine Byte -> Void)) (define (run-instruction mach opcode) (let ((op-mod-4 (bitwise-and opcode #x3)) (op-div-4 (arithmetic-shift opcode -2))) (match op-div-4 (0 (match op-mod-4 (1 (machine-add mach)) (2 (machine-sub mach)) (3 (machine-mul mach)))) (1 (match op-mod-4 (0 (machine-div mach)) (1 (machine-mod mach)) (2 (machine-lt mach)) (3 (machine-gt mach)))) (2 (match op-mod-4 (0 (machine-le mach)) (1 (machine-ge mach)) (2 (machine-eq mach)) (3 (machine-ne mach)))) (3 (match op-mod-4 (0 (machine-and mach)) (1 (machine-or mach)) (2 (machine-neg mach)) (3 (machine-not mach)))) (4 (match op-mod-4 (0 (machine-prtc mach)) (1 (machine-prti mach)) (2 (machine-prts mach)) (3 (machine-fetch mach)))) (5 (match op-mod-4 (0 (machine-store mach)) (1 (machine-push mach)) (2 (machine-jmp mach)) (3 (machine-jz mach)))))))   (: run-vm (Machine -> Void)) (define (run-vm mach) (let ((opcode-for-halt (cast (opcode-from-name "halt") Byte)) (opcode-for-add (cast (opcode-from-name "add") Byte)) (opcode-for-jz (cast (opcode-from-name "jz") Byte))) (let loop ((opcode (get-opcode mach))) (unless (= opcode opcode-for-halt) (begin (when (or (< opcode opcode-for-add) (< opcode-for-jz opcode)) (raise-user-error "unsupported opcode")) (run-instruction mach opcode) (loop (get-opcode mach)))))))   (define (usage-error) (display "Usage: vm [INPUTFILE [OUTPUTFILE]]" (current-error-port)) (newline (current-error-port)) (display "If either INPUTFILE or OUTPUTFILE is \"-\", the respective" (current-error-port)) (display " standard I/O is used." (current-error-port)) (newline (current-error-port)) (exit 1))   (: get-filenames (-> (Values String String))) (define (get-filenames) (match (current-command-line-arguments) ((vector) (values "-" "-")) ((vector inpf-filename) (values (cast inpf-filename String) "-")) ((vector inpf-filename outf-filename) (values (cast inpf-filename String) (cast outf-filename String))) (_ (usage-error) (values "" ""))))   (let-values (((inpf-filename outf-filename) (get-filenames))) (let* ((inpf (open-inpf inpf-filename)) (outf (open-outf outf-filename))) (let-values (((datasize strings-count) (read-datasize-and-strings-count inpf))) (let* ((strings (vector->immutable-vector (list->vector (read-string-literals inpf strings-count)))) (instructions (read-instructions inpf))   (mach (make-machine strings outf)))   (unless (<= datasize data-memory-size) (raise-user-error "the VM's data memory size is exceeded"))   (load-executable-memory (machine-code mach) instructions) (run-vm mach)   (unless (string=? inpf-filename "-") (close-input-port inpf)) (unless (string=? outf-filename "-") (close-output-port outf))   (exit 0)))))
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#RATFOR
RATFOR
###################################################################### # # The Rosetta Code code generator in Ratfor 77. # # # In FORTRAN 77 and therefore in Ratfor 77, there is no way to specify # that a value should be put on a call stack. Therefore there is no # way to implement recursive algorithms in Ratfor 77 (although see the # Ratfor for the "syntax analyzer" task, where a recursive language is # implemented *in* Ratfor). We are forced to use non-recursive # algorithms. # # How to deal with FORTRAN 77 input is another 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 gen-in-ratfor.r > gen-in-ratfor.f # f2c -C -Nc80 gen-in-ratfor.f # cc gen-in-ratfor.c -lf2c # ./a.out < compiler-tests/primes.ast # # With gfortran, a little differently: # # ratfor77 gen-in-ratfor.r > gen-in-ratfor.f # gfortran -fcheck=all -std=legacy gen-in-ratfor.f # ./a.out < compiler-tests/primes.ast # # # 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 wish to modify.   define(LINESZ, 256) # Size of an input line. define(OUTLSZ, 1024) # Size of an output line. define(STRNSZ, 4096) # Size of the string pool. define(NODSSZ, 4096) # Size of the nodes pool. define(STCKSZ, 4096) # Size of stacks. define(MAXVAR, 256) # Maximum number of variables. define(MAXSTR, 256) # Maximum number of strings. define(CODESZ, 16384) # Maximum size of a compiled program.   #---------------------------------------------------------------------   define(NEWLIN, 10) # The Unix newline character (ASCII LF). define(DQUOTE, 34) # The double quote character. define(BACKSL, 92) # The backslash character.   #---------------------------------------------------------------------   define(NODESZ, 3) define(NNEXTF, 1) # Index for next-free. define(NTAG, 1) # Index for the tag. # For an internal node -- define(NLEFT, 2) # Index for the left node. define(NRIGHT, 3) # Index for the right node. # For a leaf node -- define(NITV, 2) # Index for the string pool index. define(NITN, 3) # Length of the value.   define(NIL, -1) # Nil node.   define(RGT, 10000) define(STAGE2, 20000) define(STAGE3, 30000) define(STAGE4, 40000)   # The following all must be less than RGT. define(NDID, 0) define(NDSTR, 1) define(NDINT, 2) define(NDSEQ, 3) define(NDIF, 4) define(NDPRTC, 5) define(NDPRTS, 6) define(NDPRTI, 7) define(NDWHIL, 8) define(NDASGN, 9) define(NDNEG, 10) define(NDNOT, 11) define(NDMUL, 12) define(NDDIV, 13) define(NDMOD, 14) define(NDADD, 15) define(NDSUB, 16) define(NDLT, 17) define(NDLE, 18) define(NDGT, 19) define(NDGE, 20) define(NDEQ, 21) define(NDNE, 22) define(NDAND, 23) define(NDOR, 24)   define(OPHALT, 1) define(OPADD, 2) define(OPSUB, 3) define(OPMUL, 4) define(OPDIV, 5) define(OPMOD, 6) define(OPLT, 7) define(OPGT, 8) define(OPLE, 9) define(OPGE, 10) define(OPEQ, 11) define(OPNE, 12) define(OPAND, 13) define(OPOR, 14) define(OPNEG, 15) define(OPNOT, 16) define(OPPRTC, 17) define(OPPRTI, 18) define(OPPRTS, 19) define(OPFTCH, 20) define(OPSTOR, 21) define(OPPUSH, 22) define(OPJMP, 23) define(OPJZ, 24)   #---------------------------------------------------------------------   function issp (c)   # Is a character a space character?   implicit none   character c logical issp   integer ic   ic = ichar (c) issp = (ic == 32 || (9 <= ic && ic <= 13)) end   function skipsp (str, i, imax)   # Skip past spaces in a string.   implicit none   character str(*) integer i integer imax integer skipsp   logical issp   logical done   skipsp = i done = .false. while (!done) { if (imax <= skipsp) done = .true. else if (!issp (str(skipsp))) done = .true. else skipsp = skipsp + 1 } end   function skipns (str, i, imax)   # Skip past non-spaces in a string.   implicit none   character str(*) integer i integer imax integer skipns   logical issp   logical done   skipns = i done = .false. while (!done) { if (imax <= skipns) done = .true. else if (issp (str(skipns))) done = .true. else skipns = skipns + 1 } end   function trimrt (str, n)   # Find the length of a string, if one ignores trailing spaces.   implicit none   character str(*) integer n integer trimrt   logical issp   logical done   trimrt = n done = .false. while (!done) { if (trimrt == 0) done = .true. else if (!issp (str(trimrt))) done = .true. else trimrt = trimrt - 1 } end   #---------------------------------------------------------------------   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 } if (n0 == 0) { i = 0 n = 0 } else { for (j = 0; j < n0; j = j + 1) strngs(istrng + j) = src(i0 + j) i = istrng n = n0 istrng = istrng + n0 } end   #---------------------------------------------------------------------   subroutine push (stack, sp, i)   implicit none   integer stack(STCKSZ) integer sp # Stack pointer. integer i # Value to push.   if (sp == STCKSZ) { write (*, '(''stack overflow in push'')') stop } stack(sp) = i sp = sp + 1 end   function pop (stack, sp)   implicit none   integer stack(STCKSZ) integer sp # Stack pointer. integer pop   if (sp == 1) { write (*, '(''stack underflow in pop'')') stop } sp = sp - 1 pop = stack(sp) end   function nstack (sp)   implicit none   integer sp # Stack pointer. integer nstack   nstack = sp - 1 # Current cardinality of the stack. end   #---------------------------------------------------------------------   subroutine initnd (nodes, frelst)   # Initialize the nodes pool.   implicit none   integer nodes (NODESZ, NODSSZ) integer frelst # Head of the free list.   integer i   for (i = 1; i < NODSSZ; i = i + 1) nodes(NNEXTF, i) = i + 1 nodes(NNEXTF, NODSSZ) = NIL frelst = 1 end   subroutine newnod (nodes, frelst, i)   # Get the index for a new node taken from the free list.   integer nodes (NODESZ, NODSSZ) integer frelst # Head of the free list. integer i # Index of the new node.   integer j   if (frelst == NIL) { write (*, '(''nodes pool exhausted'')') stop } i = frelst frelst = nodes(NNEXTF, frelst) for (j = 1; j <= NODESZ; j = j + 1) nodes(j, i) = 0 end   subroutine frenod (nodes, frelst, i)   # Return a node to the free list.   integer nodes (NODESZ, NODSSZ) integer frelst # Head of the free list. integer i # Index of the node to free.   nodes(NNEXTF, i) = frelst frelst = i end   function strtag (str, i, n)   implicit none   character str(*) integer i, n integer strtag   character*16 s integer j   for (j = 0; j < 16; j = j + 1) if (j < n) s(j + 1 : j + 1) = str(i + j) else s(j + 1 : j + 1) = ' '   if (s == "Identifier ") strtag = NDID else if (s == "String ") strtag = NDSTR else if (s == "Integer ") strtag = NDINT else if (s == "Sequence ") strtag = NDSEQ else if (s == "If ") strtag = NDIF else if (s == "Prtc ") strtag = NDPRTC else if (s == "Prts ") strtag = NDPRTS else if (s == "Prti ") strtag = NDPRTI else if (s == "While ") strtag = NDWHIL else if (s == "Assign ") strtag = NDASGN else if (s == "Negate ") strtag = NDNEG else if (s == "Not ") strtag = NDNOT else if (s == "Multiply ") strtag = NDMUL else if (s == "Divide ") strtag = NDDIV else if (s == "Mod ") strtag = NDMOD else if (s == "Add ") strtag = NDADD else if (s == "Subtract ") strtag = NDSUB else if (s == "Less ") strtag = NDLT else if (s == "LessEqual ") strtag = NDLE else if (s == "Greater ") strtag = NDGT else if (s == "GreaterEqual ") strtag = NDGE else if (s == "Equal ") strtag = NDEQ else if (s == "NotEqual ") strtag = NDNE else if (s == "And ") strtag = NDAND else if (s == "Or ") strtag = NDOR else if (s == "; ") strtag = NIL else { write (*, '(''unrecognized input line: '', A16)') s stop } end   subroutine readln (strngs, istrng, tag, iarg, narg)   # Read a line of the AST input.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer tag # The node tag or NIL. integer iarg # Index of an argument in the string pool. integer narg # Length of an argument in the string pool.   integer trimrt integer strtag integer skipsp integer skipns   character line(LINESZ) character*20 fmt integer i, j, n   # Read a line of text as an array of characters. write (fmt, '(''('', I10, ''A)'')') LINESZ read (*, fmt) line   n = trimrt (line, LINESZ)   i = skipsp (line, 1, n + 1) j = skipns (line, i, n + 1) tag = strtag (line, i, j - i)   i = skipsp (line, j, n + 1) call addstr (strngs, istrng, line, i, (n + 1) - i, iarg, narg) end   function hasarg (tag)   implicit none   integer tag logical hasarg   hasarg = (tag == NDID || tag == NDINT || tag == NDSTR) end   subroutine rdast (strngs, istrng, nodes, frelst, iast)   # Read in the AST. A non-recursive algorithm is used.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer nodes (NODESZ, NODSSZ) # Nodes pool. integer frelst # Head of the free list. integer iast # Index of root node of the AST.   integer nstack integer pop logical hasarg   integer stack(STCKSZ) integer sp # Stack pointer. integer tag, iarg, narg integer i, j, k   sp = 1   call readln (strngs, istrng, tag, iarg, narg) if (tag == NIL) iast = NIL else { call newnod (nodes, frelst, i) iast = i nodes(NTAG, i) = tag nodes(NITV, i) = 0 nodes(NITN, i) = 0 if (hasarg (tag)) { nodes(NITV, i) = iarg nodes(NITN, i) = narg } else { call push (stack, sp, i + RGT) call push (stack, sp, i) while (nstack (sp) != 0) { j = pop (stack, sp) k = mod (j, RGT) call readln (strngs, istrng, tag, iarg, narg) if (tag == NIL) i = NIL else { call newnod (nodes, frelst, i) nodes(NTAG, i) = tag if (hasarg (tag)) { nodes(NITV, i) = iarg nodes(NITN, i) = narg } else { call push (stack, sp, i + RGT) call push (stack, sp, i) } } if (j == k) nodes(NLEFT, k) = i else nodes(NRIGHT, k) = i } } } end   #---------------------------------------------------------------------   subroutine flushl (outbuf, noutbf)   # Flush a line from the output buffer.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf.   character*20 fmt integer i   if (noutbf == 0) write (*, '()') else { write (fmt, 1000) noutbf 1000 format ('(', I10, 'A)') write (*, fmt) (outbuf(i), i = 1, noutbf) noutbf = 0 } end   subroutine wrtchr (outbuf, noutbf, ch)   # Write a character to output.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. character ch # The character to output.   # This routine silently truncates anything that goes past the buffer # boundary.   if (ch == char (NEWLIN)) call flushl (outbuf, noutbf) else if (noutbf < OUTLSZ) { noutbf = noutbf + 1 outbuf(noutbf) = ch } end   subroutine wrtstr (outbuf, noutbf, str, i, n)   # Write a substring to output.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. character str(*) # The string from which to output. integer i, n # Index and length of the substring.   integer j   for (j = 0; j < n; j = j + 1) call wrtchr (outbuf, noutbf, str(i + j)) end   subroutine wrtint (outbuf, noutbf, ival, colcnt)   # Write a non-negative integer to output.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. integer ival # The non-negative integer to print. integer colcnt # Column count, or zero for free format.   integer skipsp   character*40 buf integer i, j   write (buf, '(I40)') ival i = skipsp (buf, 1, 41) if (0 < colcnt) for (j = 1; j < colcnt - (40 - i); j = j + 1) call wrtchr (outbuf, noutbf, ' ') while (i <= 40) { call wrtchr (outbuf, noutbf, buf(i:i)) i = i + 1 } end   #---------------------------------------------------------------------   define(VARSZ, 3) define(VNAMEI, 1) # Variable name's index in the string pool. define(VNAMEN, 2) # Length of the name. define(VVALUE, 3) # Variable's number in the VM's data pool.   function fndvar (vars, numvar, strngs, istrng, i0, n0)   implicit none   integer vars(VARSZ, MAXVAR) # Variables. integer numvar # Number of variables. character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer i0, n0 # Index and length in the string pool. integer fndvar # The location of the variable.   integer j, k integer i, n logical done1 logical done2   j = 1 done1 = .false. while (!done1) if (j == numvar + 1) done1 = .true. else if (n0 == vars(VNAMEN, j)) { k = 0 done2 = .false. while (!done2) if (n0 <= k) done2 = .true. else if (strngs(i0 + k) == strngs(vars(VNAMEI, j) + k)) k = k + 1 else done2 = .true. if (k < n0) j = j + 1 else { done2 = .true. done1 = .true. } } else j = j + 1   if (j == numvar + 1) { if (numvar == MAXVAR) { write (*, '(''too many variables'')') stop } numvar = numvar + 1 call addstr (strngs, istrng, strngs, i0, n0, i, n) vars(VNAMEI, numvar) = i vars(VNAMEN, numvar) = n vars(VVALUE, numvar) = numvar - 1 fndvar = numvar } else fndvar = j end   define(STRSZ, 3) define(STRI, 1) # String's index in this program's string pool. define(STRN, 2) # Length of the string. define(STRNO, 3) # String's number in the VM's string pool.   function fndstr (strs, numstr, strngs, istrng, i0, n0)   implicit none   integer strs(STRSZ, MAXSTR) # Strings for the VM's string pool. integer numstr # Number of such strings. character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer i0, n0 # Index and length in the string pool. integer fndstr # The location of the string in the VM's string pool.   integer j, k integer i, n logical done1 logical done2   j = 1 done1 = .false. while (!done1) if (j == numstr + 1) done1 = .true. else if (n0 == strs(STRN, j)) { k = 0 done2 = .false. while (!done2) if (n0 <= k) done2 = .true. else if (strngs(i0 + k) == strngs(strs(STRI, j) + k)) k = k + 1 else done2 = .true. if (k < n0) j = j + 1 else { done2 = .true. done1 = .true. } } else j = j + 1   if (j == numstr + 1) { if (numstr == MAXSTR) { write (*, '(''too many string literals'')') stop } numstr = numstr + 1 call addstr (strngs, istrng, strngs, i0, n0, i, n) strs(STRI, numstr) = i strs(STRN, numstr) = n strs(STRNO, numstr) = numstr - 1 fndstr = numstr } else fndstr = j end   function strint (strngs, i, n)   # Convert a string to a non-negative integer.   implicit none   character strngs(STRNSZ) # String pool. integer i, n integer strint   integer j   strint = 0 for (j = 0; j < n; j = j + 1) strint = (10 * strint) + (ichar (strngs(i + j)) - ichar ('0')) end   subroutine put1 (code, ncode, i, opcode)   # Store a 1-byte operation.   implicit none   integer code(0 : CODESZ - 1) # Generated code. integer ncode # Number of VM bytes in the code. integer i # Address to put the code at. integer opcode   if (CODESZ - i < 1) { write (*, '(''address beyond the size of memory'')') stop } code(i) = opcode ncode = max (ncode, i + 1) end   subroutine put5 (code, ncode, i, opcode, ival)   # Store a 5-byte operation.   implicit none   integer code(0 : CODESZ - 1) # Generated code. integer ncode # Number of VM bytes in the code. integer i # Address to put the code at. integer opcode integer ival # Immediate integer value.   if (CODESZ - i < 5) { write (*, '(''address beyond the size of memory'')') stop } code(i) = opcode code(i + 1) = ival # Do not bother to break the integer into bytes. code(i + 2) = 0 code(i + 3) = 0 code(i + 4) = 0 ncode = max (ncode, i + 5) end   subroutine compil (vars, numvar, _ strs, numstr, _ strngs, istrng, _ nodes, frelst, _ code, ncode, iast)   # Compile the AST to virtual machine code. The algorithm employed is # non-recursive.   implicit none   integer vars(VARSZ, MAXVAR) # Variables. integer numvar # Number of variables. integer strs(STRSZ, MAXSTR) # Strings for the VM's string pool. integer numstr # Number of such strings. character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer nodes (NODESZ, NODSSZ) # Nodes pool. integer frelst # Head of the free list. integer code(0 : CODESZ - 1) # Generated code. integer ncode # Number of VM bytes in the code. integer iast # Root node of the AST.   integer fndvar integer fndstr integer nstack integer pop integer strint   integer xstack(STCKSZ) # Node stack. integer ixstck # Node stack pointer. integer i integer i0, n0 integer tag integer ivar integer inode1, inode2, inode3 integer addr1, addr2   ixstck = 1 call push (xstack, ixstck, iast) while (nstack (ixstck) != 0) { i = pop (xstack, ixstck) if (i == NIL) tag = NIL else tag = nodes(NTAG, i) if (tag == NIL) continue else if (tag < STAGE2) { if (tag == NDSEQ) { if (nodes(NRIGHT, i) != NIL) call push (xstack, ixstck, nodes(NRIGHT, i)) if (nodes(NLEFT, i) != NIL) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDID) { # Fetch the value of a variable. i0 = nodes(NITV, i) n0 = nodes(NITN, i) ivar = fndvar (vars, numvar, strngs, istrng, i0, n0) ivar = vars(VVALUE, ivar) call put5 (code, ncode, ncode, OPFTCH, ivar) } else if (tag == NDINT) { # Push the value of an integer literal. i0 = nodes(NITV, i) n0 = nodes(NITN, i) call put5 (code, ncode, ncode, OPPUSH, _ strint (strngs, i0, n0)) } else if (tag == NDNEG) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDNEG + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDNOT) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDNOT + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDAND) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDAND + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDOR) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDOR + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDADD) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDADD + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDSUB) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDSUB + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDMUL) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDMUL + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDDIV) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDDIV + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDMOD) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDMOD + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDLT) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDLT + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDLE) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDLE + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDGT) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDGT + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDGE) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDGE + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDEQ) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDEQ + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDNE) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDNE + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDASGN) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDASGN + STAGE2 nodes(NITV, inode1) = nodes(NITV, nodes(NLEFT, i)) nodes(NITN, inode1) = nodes(NITN, nodes(NLEFT, i)) call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) } else if (tag == NDPRTS) { i0 = nodes(NITV, nodes(NLEFT, i)) n0 = nodes(NITN, nodes(NLEFT, i)) ivar = fndstr (strs, numstr, strngs, istrng, i0, n0) ivar = strs(STRNO, ivar) call put5 (code, ncode, ncode, OPPUSH, ivar) call put1 (code, ncode, ncode, OPPRTS) } else if (tag == NDPRTC) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDPRTC + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDPRTI) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDPRTI + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDWHIL) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDWHIL + STAGE2 nodes(NLEFT, inode1) = nodes(NRIGHT, i) # Loop body. nodes(NRIGHT, inode1) = ncode # Addr. of top of loop. call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDIF) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDIF + STAGE2 # The "then" and "else" clauses, respectively: nodes(NLEFT, inode1) = nodes(NLEFT, nodes(NRIGHT, i)) nodes(NRIGHT, inode1) = nodes(NRIGHT, nodes(NRIGHT, i)) call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } } else { if (tag == NDNEG + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPNEG) } else if (tag == NDNOT + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPNOT) } else if (tag == NDAND + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPAND) } else if (tag == NDOR + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPOR) } else if (tag == NDADD + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPADD) } else if (tag == NDSUB + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPSUB) } else if (tag == NDMUL + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPMUL) } else if (tag == NDDIV + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPDIV) } else if (tag == NDMOD + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPMOD) } else if (tag == NDLT + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPLT) } else if (tag == NDLE + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPLE) } else if (tag == NDGT + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPGT) } else if (tag == NDGE + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPGE) } else if (tag == NDEQ + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPEQ) } else if (tag == NDNE + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPNE) } else if (tag == NDASGN + STAGE2) { i0 = nodes(NITV, i) n0 = nodes(NITN, i) call frenod (nodes, frelst, i) ivar = fndvar (vars, numvar, strngs, istrng, i0, n0) ivar = vars(VVALUE, ivar) call put5 (code, ncode, ncode, OPSTOR, ivar) } else if (tag == NDPRTC + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPPRTC) } else if (tag == NDPRTI + STAGE2) { call frenod (nodes, frelst, i) call put1 (code, ncode, ncode, OPPRTI) } else if (tag == NDWHIL + STAGE2) { inode1 = nodes(NLEFT, i) # Loop body. addr1 = nodes(NRIGHT, i) # Addr. of top of loop. call frenod (nodes, frelst, i) call put5 (code, ncode, ncode, OPJZ, 0) call newnod (nodes, frelst, inode2) nodes(NTAG, inode2) = NDWHIL + STAGE3 nodes(NLEFT, inode2) = addr1 # Top of loop. nodes(NRIGHT, inode2) = ncode - 4 # Fixup address. call push (xstack, ixstck, inode2) call push (xstack, ixstck, inode1) } else if (tag == NDWHIL + STAGE3) { addr1 = nodes(NLEFT, i) # Top of loop. addr2 = nodes(NRIGHT, i) # Fixup address. call frenod (nodes, frelst, i) call put5 (code, ncode, ncode, OPJMP, addr1) code(addr2) = ncode } else if (tag == NDIF + STAGE2) { inode1 = nodes(NLEFT, i) # "Then" clause. inode2 = nodes(NRIGHT, i) # "Else" clause. call frenod (nodes, frelst, i) call put5 (code, ncode, ncode, OPJZ, 0) call newnod (nodes, frelst, inode3) nodes(NTAG, inode3) = NDIF + STAGE3 nodes(NLEFT, inode3) = ncode - 4 # Fixup address. nodes(NRIGHT, inode3) = inode2 # "Else" clause. call push (xstack, ixstck, inode3) call push (xstack, ixstck, inode1) } else if (tag == NDIF + STAGE3) { addr1 = nodes(NLEFT, i) # Fixup address. inode1 = nodes(NRIGHT, i) # "Else" clause. call frenod (nodes, frelst, i) if (inode2 == NIL) code(addr1) = ncode else { call put5 (code, ncode, ncode, OPJMP, 0) addr2 = ncode - 4 # Another fixup address. code(addr1) = ncode call newnod (nodes, frelst, inode2) nodes(NTAG, inode2) = NDIF + STAGE4 nodes(NLEFT, inode2) = addr2 call push (xstack, ixstck, inode2) call push (xstack, ixstck, inode1) } } else if (tag == NDIF + STAGE4) { addr1 = nodes(NLEFT, i) # Fixup address. call frenod (nodes, frelst, i) code(addr1) = ncode } } } call put1 (code, ncode, ncode, OPHALT) end   function opname (opcode)   implicit none   integer opcode character*8 opname   if (opcode == OPHALT) opname = 'halt ' else if (opcode == OPADD) opname = 'add ' else if (opcode == OPSUB) opname = 'sub ' else if (opcode == OPMUL) opname = 'mul ' else if (opcode == OPDIV) opname = 'div ' else if (opcode == OPMOD) opname = 'mod ' else if (opcode == OPLT) opname = 'lt ' else if (opcode == OPGT) opname = 'gt ' else if (opcode == OPLE) opname = 'le ' else if (opcode == OPGE) opname = 'ge ' else if (opcode == OPEQ) opname = 'eq ' else if (opcode == OPNE) opname = 'ne ' else if (opcode == OPAND) opname = 'and ' else if (opcode == OPOR) opname = 'or ' else if (opcode == OPNEG) opname = 'neg ' else if (opcode == OPNOT) opname = 'not ' else if (opcode == OPPRTC) opname = 'prtc ' else if (opcode == OPPRTI) opname = 'prti ' else if (opcode == OPPRTS) opname = 'prts ' else if (opcode == OPFTCH) opname = 'fetch ' else if (opcode == OPSTOR) opname = 'store ' else if (opcode == OPPUSH) opname = 'push ' else if (opcode == OPJMP) opname = 'jmp ' else if (opcode == OPJZ) opname = 'jz ' else { write (*, '(''Unrecognized opcode: '', I5)') opcode stop } end   subroutine prprog (numvar, strs, numstr, strngs, istrng, _ code, ncode, outbuf, noutbf)   implicit none   integer numvar # Number of variables. integer strs(STRSZ, MAXSTR) # Strings for the VM's string pool. integer numstr # Number of such strings. character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer code(0 : CODESZ - 1) # Generated code. integer ncode # Number of VM bytes in the code. character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf.   character*8 opname   integer i0, n0 integer i, j integer opcode character*8 name   character buf(20) buf(1) = 'D' buf(2) = 'a' buf(3) = 't' buf(4) = 'a' buf(5) = 's' buf(6) = 'i' buf(7) = 'z' buf(8) = 'e' buf(9) = ':' buf(10) = ' ' call wrtstr (outbuf, noutbf, buf, 1, 10) call wrtint (outbuf, noutbf, numvar, 0) buf(1) = ' ' buf(2) = 'S' buf(3) = 't' buf(4) = 'r' buf(5) = 'i' buf(6) = 'n' buf(7) = 'g' buf(8) = 's' buf(9) = ':' buf(10) = ' ' call wrtstr (outbuf, noutbf, buf, 1, 10) call wrtint (outbuf, noutbf, numstr, 0) call wrtchr (outbuf, noutbf, char (NEWLIN))   for (i = 1; i <= numstr; i = i + 1) { i0 = strs(STRI, i) n0 = strs(STRN, i) call wrtstr (outbuf, noutbf, strngs, i0, n0) call wrtchr (outbuf, noutbf, char (NEWLIN)) }   i = 0 while (i != ncode) { opcode = code(i) name = opname (opcode) call wrtint (outbuf, noutbf, i, 10) for (j = 1; j <= 2; j = j + 1) call wrtchr (outbuf, noutbf, ' ') for (j = 1; j <= 8; j = j + 1) { if (opcode == OPFTCH _ || opcode == OPSTOR _ || opcode == OPPUSH _ || opcode == OPJMP _ || opcode == OPJZ) call wrtchr (outbuf, noutbf, name(j:j)) else if (name(j:j) != ' ') call wrtchr (outbuf, noutbf, name(j:j)) } if (opcode == OPPUSH) { call wrtint (outbuf, noutbf, code(i + 1), 0) i = i + 5 } else if (opcode == OPFTCH || opcode == OPSTOR) { call wrtchr (outbuf, noutbf, '[') call wrtint (outbuf, noutbf, code(i + 1), 0) call wrtchr (outbuf, noutbf, ']') i = i + 5 } else if (opcode == OPJMP || opcode == OPJZ) { call wrtchr (outbuf, noutbf, '(') call wrtint (outbuf, noutbf, code(i + 1) - (i + 1), 0) call wrtchr (outbuf, noutbf, ')') call wrtchr (outbuf, noutbf, ' ') call wrtint (outbuf, noutbf, code(i + 1), 0) i = i + 5 } else i = i + 1 call wrtchr (outbuf, noutbf, char (NEWLIN)) } end   #---------------------------------------------------------------------   program gen   implicit none   integer vars(VARSZ, MAXVAR) # Variables. integer numvar # Number of variables. integer strs(STRSZ, MAXSTR) # Strings for the VM's string pool. integer numstr # Number of such strings. character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer nodes (NODESZ, NODSSZ) # Nodes pool. integer frelst # Head of the free list. character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. integer code(0 : CODESZ - 1) # Generated code. integer ncode # Number of VM bytes in the code. integer iast # Root node of the AST.   numvar = 0 numstr = 0 istrng = 1 noutbf = 0 ncode = 0   call initnd (nodes, frelst) call rdast (strngs, istrng, nodes, frelst, iast)   call compil (vars, numvar, strs, numstr, _ strngs, istrng, nodes, frelst, _ code, ncode, iast) call prprog (numvar, strs, numstr, strngs, istrng, _ code, ncode, outbuf, noutbf)   if (noutbf != 0) call flushl (outbuf, noutbf) end   ######################################################################
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Quackery
Quackery
$ "A short string of" $ "A slightly longer string of"   2dup size dip size > if swap dup echo$ sp size echo say " characters." cr dup echo$ sp size echo say " characters." cr cr   ' [ $ "From troubles of the world I turn to ducks," $ "Beautiful comical things" $ "Sleeping or curled" $ "Their heads beneath white wings" $ "By water cool," $ "Or finding curious things" $ "To eat in various mucks" $ "Beneath the pool," ] [] swap witheach [ do nested join ]   sortwith [ size dip size < ] witheach [ echo$ cr ]
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raku
Raku
say 'Strings (👨‍👩‍👧‍👦, 🤔🇺🇸, BOGUS!) sorted: "longest" first:'; say "$_: characters:{.chars}, Unicode code points:{.codes}, UTF-8 bytes:{.encode('UTF8').bytes}, UTF-16 bytes:{.encode('UTF16').bytes}" for <👨‍👩‍👧‍👦 BOGUS! 🤔🇺🇸>.sort: -*.chars;
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.
#Elixir
Elixir
defmodule Conway do def game_of_life(name, size, generations, initial_life\\nil) do board = seed(size, initial_life) print_board(board, name, size, 0) reason = generate(name, size, generations, board, 1) case reason do  :all_dead -> "no more life."  :static -> "no movement" _ -> "specified lifetime ended" end |> IO.puts IO.puts "" end   defp new_board(n) do for x <- 1..n, y <- 1..n, into: %{}, do: {{x,y}, 0} end   defp seed(n, points) do if points do points else # randomly seed board (for x <- 1..n, y <- 1..n, do: {x,y}) |> Enum.take_random(10) end |> Enum.reduce(new_board(n), fn pos,acc -> %{acc | pos => 1} end) end   defp generate(_, _, generations, _, gen) when generations < gen, do: :ok defp generate(name, size, generations, board, gen) do new = evolve(board, size) print_board(new, name, size, gen) cond do barren?(new) -> :all_dead board == new -> :static true -> generate(name, size, generations, new, gen+1) end end   defp evolve(board, n) do for x <- 1..n, y <- 1..n, into: %{}, do: {{x,y}, fate(board, x, y, n)} end   defp fate(board, x, y, n) do irange = max(1, x-1) .. min(x+1, n) jrange = max(1, y-1) .. min(y+1, n) sum = ((for i <- irange, j <- jrange, do: board[{i,j}]) |> Enum.sum) - board[{x,y}] cond do sum == 3 -> 1 sum == 2 and board[{x,y}] == 1 -> 1 true -> 0 end end   defp barren?(board) do Enum.all?(board, fn {_,v} -> v == 0 end) end   defp print_board(board, name, n, generation) do IO.puts "#{name}: generation #{generation}" Enum.each(1..n, fn y -> Enum.map(1..n, fn x -> if board[{x,y}]==1, do: "#", else: "." end) |> IO.puts end) end end   Conway.game_of_life("blinker", 3, 2, [{2,1},{2,2},{2,3}]) Conway.game_of_life("glider", 4, 4, [{2,1},{3,2},{1,3},{2,3},{3,3}]) Conway.game_of_life("random", 5, 10)
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Tcl
Tcl
array set point {x 4 y 5} set point(y) 7 puts "Point is {$point(x),$point(y)}" # => Point is {4,7}
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#TI-89_BASIC
TI-89 BASIC
(defstruct point nil (x 0) (y 0))
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.
#Bori
Bori
  if (i == 0) return "zero"; elif (i % 2) return "odd"; else return "even";  
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
#FreeBASIC
FreeBASIC
  ' FB 1.05.0 Win64   Function AllEqual(strings() As String) As Boolean Dim length As Integer = UBound(strings) - LBound(strings) + 1 If length < 2 Then Return False For i As Integer = LBound(strings) + 1 To UBound(strings) If strings(i - 1) <> strings(i) Then Return False Next Return True End Function   Function AllAscending(strings() As String) As Boolean Dim length As Integer = UBound(strings) - LBound(strings) + 1 If length < 2 Then Return False For i As Integer = LBound(strings) + 1 To UBound(strings) If strings(i - 1) >= strings(i) Then Return False Next Return True 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
#F.C5.8Drmul.C3.A6
Fōrmulæ
package cmp   func AllEqual(strings []string) bool { for _, s := range strings { if s != strings[0] { return false } } return true }   func AllLessThan(strings []string) bool { for i := 1; i < len(strings); i++ { if !(strings[i - 1] < s) { return false } } return true }
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.
#C.23
C#
using System; using System.Linq;   namespace CommaQuibbling { internal static class Program { #region Static Members private static string Quibble(string[] input) { return String.Format("{{{0}}}", String.Join("", input.Reverse().Zip( new [] { "", " and " }.Concat(Enumerable.Repeat(", ", int.MaxValue)), (x, y) => x + y).Reverse())); }     private static void Main() { Console.WriteLine( Quibble( new string[] {} ) ); Console.WriteLine( Quibble( new[] {"ABC"} ) ); Console.WriteLine( Quibble( new[] {"ABC", "DEF"} ) ); Console.WriteLine( Quibble( new[] {"ABC", "DEF", "G", "H"} ) );   Console.WriteLine( "< Press Any Key >" ); Console.ReadKey(); }   #endregion } }
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
#Common_Lisp
Common Lisp
(defun combinations (xs k) (let ((x (car xs))) (cond ((null xs) nil) ((= k 1) (mapcar #'list xs)) (t (append (mapcar (lambda (ys) (cons x ys)) (combinations xs (1- k))) (combinations (cdr xs) k))))))  
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Icon_and_Unicon
Icon and Unicon
procedure main() write("P(4,2) = ",P(4,2)) write("P(8,2) = ",P(8,2)) write("P(10,8) = ",P(10,8)) write("C(10,8) = ",C(10,8)) write("C(20,8) = ",C(20,8)) write("C(60,58) = ",C(60,58)) write("P(1000,10) = ",P(1000,10)) write("P(1000,20) = ",P(1000,20)) write("P(15000,2) = ",P(15000,2)) write("C(1000,10) = ",C(1000,10)) write("C(1000,999) = ",C(1000,999)) write("C(1000,1000) = ",C(1000,1000)) write("C(15000,14998) = ",C(15000,14998)) end   procedure C(n,k) every (d:=1) *:= 2 to k return P(n,k)/d end   procedure P(n,k) every (p:=1) *:= (n-k+1) to n return p end
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is also used to refer to the first stage of a lexer). Task[edit] Create a lexical analyzer for the simple programming language specified below. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a lexer module/library/class, it would be great if two versions of the solution are provided: One without the lexer module, and one with. Input Specification The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens: Operators Name Common name Character sequence Op_multiply multiply * Op_divide divide / Op_mod mod % Op_add plus + Op_subtract minus - Op_negate unary minus - Op_less less than < Op_lessequal less than or equal <= Op_greater greater than > Op_greaterequal greater than or equal >= Op_equal equal == Op_notequal not equal != Op_not unary not ! Op_assign assignment = Op_and logical and && Op_or logical or ¦¦ The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task. Symbols Name Common name Character LeftParen left parenthesis ( RightParen right parenthesis ) LeftBrace left brace { RightBrace right brace } Semicolon semi-colon ; Comma comma , Keywords Name Character sequence Keyword_if if Keyword_else else Keyword_while while Keyword_print print Keyword_putc putc Identifiers and literals These differ from the the previous tokens, in that each occurrence of them has a value associated with it. Name Common name Format description Format regex Value Identifier identifier one or more letter/number/underscore characters, but not starting with a number [_a-zA-Z][_a-zA-Z0-9]* as is Integer integer literal one or more digits [0-9]+ as is, interpreted as a number Integer char literal exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes '([^'\n]|\\n|\\\\)' the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n' String string literal zero or more characters (anything except newline or double quote), enclosed by double quotes "[^"\n]*" the characters without the double quotes and with escape sequences converted For char and string literals, the \n escape sequence is supported to represent a new-line character. For char and string literals, to represent a backslash, use \\. No other special sequences are supported. This means that: Char literals cannot represent a single quote character (value 39). String literals cannot represent strings containing double quote characters. Zero-width tokens Name Location End_of_input when the end of the input stream is reached White space Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below. "Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =). Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge. This means: keywords, identifiers, and integer literals. e.g. ifprint is recognized as an identifier, instead of the keywords if and print. e.g. 42fred is invalid, and neither recognized as a number nor an identifier. Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value). e.g. & & is invalid, and not interpreted as the && operator. For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions: if ( p /* meaning n is prime */ ) { print ( n , " " ) ; count = count + 1 ; /* number of primes found so far */ } if(p){print(n," ");count=count+1;} Complete list of token names End_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract Op_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal Op_equal Op_notequal Op_assign Op_and Op_or Keyword_if Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen LeftBrace RightBrace Semicolon Comma Identifier Integer String Output Format The program output should be a sequence of lines, each consisting of the following whitespace-separated fields: the line number where the token starts the column number where the token starts the token name the token value (only for Identifier, Integer, and String tokens) the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement. This task is intended to be used as part of a pipeline, with the other compiler tasks - for example: lex < hello.t | parse | gen | vm Or possibly: lex hello.t lex.out parse lex.out parse.out gen parse.out gen.out vm gen.out This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs. Diagnostics The following error conditions should be caught: Error Example Empty character constant '' Unknown escape sequence. \r Multi-character constant. 'xx' End-of-file in comment. Closing comment characters not found. End-of-file while scanning string literal. Closing string character not found. End-of-line while scanning string literal. Closing string character not found before end-of-line. Unrecognized character. | Invalid number. Starts like a number, but ends in non-numeric characters. 123abc Test Cases Input Output Test Case 1: /* Hello world */ print("Hello, World!\n"); 4 1 Keyword_print 4 6 LeftParen 4 7 String "Hello, World!\n" 4 24 RightParen 4 25 Semicolon 5 1 End_of_input Test Case 2: /* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, "\n"); 4 1 Identifier phoenix_number 4 16 Op_assign 4 18 Integer 142857 4 24 Semicolon 5 1 Keyword_print 5 6 LeftParen 5 7 Identifier phoenix_number 5 21 Comma 5 23 String "\n" 5 27 RightParen 5 28 Semicolon 6 1 End_of_input Test Case 3: /* All lexical tokens - not syntactically correct, but that will have to wait until syntax analysis */ /* Print */ print /* Sub */ - /* Putc */ putc /* Lss */ < /* If */ if /* Gtr */ > /* Else */ else /* Leq */ <= /* While */ while /* Geq */ >= /* Lbrace */ { /* Eq */ == /* Rbrace */ } /* Neq */ != /* Lparen */ ( /* And */ && /* Rparen */ ) /* Or */ || /* Uminus */ - /* Semi */ ; /* Not */ ! /* Comma */ , /* Mul */ * /* Assign */ = /* Div */ / /* Integer */ 42 /* Mod */ % /* String */ "String literal" /* Add */ + /* Ident */ variable_name /* character literal */ '\n' /* character literal */ '\\' /* character literal */ ' ' 5 16 Keyword_print 5 40 Op_subtract 6 16 Keyword_putc 6 40 Op_less 7 16 Keyword_if 7 40 Op_greater 8 16 Keyword_else 8 40 Op_lessequal 9 16 Keyword_while 9 40 Op_greaterequal 10 16 LeftBrace 10 40 Op_equal 11 16 RightBrace 11 40 Op_notequal 12 16 LeftParen 12 40 Op_and 13 16 RightParen 13 40 Op_or 14 16 Op_subtract 14 40 Semicolon 15 16 Op_not 15 40 Comma 16 16 Op_multiply 16 40 Op_assign 17 16 Op_divide 17 40 Integer 42 18 16 Op_mod 18 40 String "String literal" 19 16 Op_add 19 40 Identifier variable_name 20 26 Integer 10 21 26 Integer 92 22 26 Integer 32 23 1 End_of_input Test Case 4: /*** test printing, embedded \n and comments with lots of '*' ***/ print(42); print("\nHello World\nGood Bye\nok\n"); print("Print a slash n - \\n.\n"); 2 1 Keyword_print 2 6 LeftParen 2 7 Integer 42 2 9 RightParen 2 10 Semicolon 3 1 Keyword_print 3 6 LeftParen 3 7 String "\nHello World\nGood Bye\nok\n" 3 38 RightParen 3 39 Semicolon 4 1 Keyword_print 4 6 LeftParen 4 7 String "Print a slash n - \\n.\n" 4 33 RightParen 4 34 Semicolon 5 1 End_of_input Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Syntax Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#Euphoria
Euphoria
include std/io.e include std/map.e include std/types.e include std/convert.e   constant true = 1, false = 0, EOF = -1   enum tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, tk_Integer, tk_String   constant all_syms = {"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"}   integer input_file, the_ch = ' ', the_col = 0, the_line = 1 sequence symbols map key_words = new()   procedure error(sequence format, sequence data) printf(STDOUT, format, data) abort(1) end procedure   -- get the next character from the input function next_ch() the_ch = getc(input_file) the_col += 1 if the_ch = '\n' then the_line += 1 the_col = 0 end if return the_ch end function   -- 'x' - character constants function char_lit(integer err_line, integer err_col) integer n = next_ch() -- skip opening quote if the_ch = '\'' then error("%d %d empty character constant", {err_line, err_col}) elsif the_ch = '\\' then next_ch() if the_ch = 'n' then n = 10 elsif the_ch = '\\' then n = '\\' else error("%d %d unknown escape sequence \\%c", {err_line, err_col, the_ch}) end if end if if next_ch() != '\'' then error("%d %d multi-character constant", {err_line, err_col}) end if next_ch() return {tk_Integer, err_line, err_col, n} end function   -- process divide or comments function div_or_cmt(integer err_line, integer err_col) if next_ch() != '*' then return {tk_Div, err_line, err_col} end if   -- comment found next_ch() while true do if the_ch = '*' then if next_ch() = '/' then next_ch() return get_tok() end if elsif the_ch = EOF then error("%d %d EOF in comment", {err_line, err_col}) else next_ch() end if end while end function   -- "string" function string_lit(integer start, integer err_line, integer err_col) string text = ""   while next_ch() != start do if the_ch = EOF then error("%d %d EOF while scanning string literal", {err_line, err_col}) end if if the_ch = '\n' then error("%d %d EOL while scanning string literal", {err_line, err_col}) end if text &= the_ch end while   next_ch() return {tk_String, err_line, err_col, text} end function   -- handle identifiers and integers function ident_or_int(integer err_line, integer err_col) integer n, is_number = true string text = ""   while t_alnum(the_ch) or the_ch = '_' do text &= the_ch if not t_digit(the_ch) then is_number = false end if next_ch() end while   if length(text) = 0 then error("%d %d ident_or_int: unrecognized character: (%d) '%s'", {err_line, err_col, the_ch, the_ch}) end if   if t_digit(text[1]) then if not is_number then error("%d %d invalid number: %s", {err_line, err_col, text}) end if n = to_integer(text) return {tk_Integer, err_line, err_col, n} end if   if has(key_words, text) then return {get(key_words, text), err_line, err_col} end if   return {tk_Ident, err_line, err_col, text} end function   -- look ahead for '>=', etc. function follow(integer expect, integer ifyes, integer ifno, integer err_line, integer err_col) if next_ch() = expect then next_ch() return {ifyes, err_line, err_col} end if   if ifno = tk_EOI then error("%d %d follow: unrecognized character: (%d)", {err_line, err_col, the_ch}) end if   return {ifno, err_line, err_col} end function   -- return the next token type function get_tok() while t_space(the_ch) do next_ch() end while   integer err_line = the_line integer err_col = the_col   switch the_ch do case EOF then return {tk_EOI, err_line, err_col} case '/' then return div_or_cmt(err_line, err_col) case '\'' then return char_lit(err_line, err_col)   case '<' then return follow('=', tk_Leq, tk_Lss, err_line, err_col) case '>' then return follow('=', tk_Geq, tk_Gtr, err_line, err_col) case '=' then return follow('=', tk_Eq, tk_Assign, err_line, err_col) case '!' then return follow('=', tk_Neq, tk_Not, err_line, err_col) case '&' then return follow('&', tk_And, tk_EOI, err_line, err_col) case '|' then return follow('|', tk_Or, tk_EOI, err_line, err_col)   case '"' then return string_lit(the_ch, err_line, err_col) case else integer sym = symbols[the_ch] if sym  != tk_EOI then next_ch() return {sym, err_line, err_col} end if return ident_or_int(err_line, err_col) end switch end function   procedure init() put(key_words, "else", tk_Else) put(key_words, "if", tk_If) put(key_words, "print", tk_Print) put(key_words, "putc", tk_Putc) put(key_words, "while", tk_While)   symbols = repeat(tk_EOI, 256) symbols['{'] = tk_Lbrace symbols['}'] = tk_Rbrace symbols['('] = tk_Lparen symbols[')'] = tk_Rparen symbols['+'] = tk_Add symbols['-'] = tk_Sub symbols['*'] = tk_Mul symbols['%'] = tk_Mod symbols[';'] = tk_Semi symbols[','] = tk_Comma end procedure   procedure main(sequence cl) sequence file_name   input_file = STDIN if length(cl) > 2 then file_name = cl[3] input_file = open(file_name, "r") if input_file = -1 then error("Could not open %s", {file_name}) end if end if init() sequence t loop do t = get_tok() printf(STDOUT, "%5d  %5d %-8s", {t[2], t[3], all_syms[t[1]]}) switch t[1] do case tk_Integer then printf(STDOUT, "  %5d\n", {t[4]}) case tk_Ident then printf(STDOUT, " %s\n", {t[4]}) case tk_String then printf(STDOUT, " \"%s\"\n", {t[4]}) case else printf(STDOUT, "\n") end switch until t[1] = tk_EOI end loop end procedure   main(command_line())
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"
#D
D
void main(in string[] args) { import std.stdio;   foreach (immutable i, arg; args[1 .. $]) writefln("#%2d : %s", i + 1, 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"
#Dart
Dart
main(List<String> args) { for(var arg in args) print(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.)
#Axe
Axe
.This is a single-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.)
#Babel
Babel
  -- This is a line-comment   # This is a block-comment It goes until de-dent   dedent: 0x42 -- The comment block above is now closed  
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#Raku
Raku
my @CODE = q:to/END/.lines; Datasize: 3 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (68) 65 # jump value adjusted 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-87) 10 # jump value adjusted 65 halt END   my (@stack, @strings, @data, $memory); my $pc = 0;   (@CODE.shift) ~~ /'Datasize:' \s+ (\d+) \s+ 'Strings:' \s+ (\d+)/ or die "bad header"; my $w = $0; # 'wordsize' of op-codes and 'width' of data values @strings.push: (my $s = @CODE.shift) eq '"\n"' ?? "\n" !! $s.subst(/'"'/, '', :g) for 1..$1;   sub value { substr($memory, ($pc += $w) - $w, $w).trim }   my %ops = ( 'no-op' => sub { }, 'add' => sub { @stack[*-2] += @stack.pop }, 'sub' => sub { @stack[*-2] -= @stack.pop }, 'mul' => sub { @stack[*-2] *= @stack.pop }, 'div' => sub { @stack[*-2] /= @stack.pop }, 'mod' => sub { @stack[*-2] %= @stack.pop }, 'neg' => sub { @stack[*-1] = - @stack[*-1] }, 'and' => sub { @stack[*-2] &&= @stack[*-1]; @stack.pop }, 'or' => sub { @stack[*-2] ||= @stack[*-1]; @stack.pop }, 'not' => sub { @stack[*-1] = @stack[*-1] ?? 0 !! 1 }, 'lt' => sub { @stack[*-1] = @stack[*-2] < @stack.pop ?? 1 !! 0 }, 'gt' => sub { @stack[*-1] = @stack[*-2] > @stack.pop ?? 1 !! 0 }, 'le' => sub { @stack[*-1] = @stack[*-2] <= @stack.pop ?? 1 !! 0 }, 'ge' => sub { @stack[*-1] = @stack[*-2] >= @stack.pop ?? 1 !! 0 }, 'ne' => sub { @stack[*-1] = @stack[*-2] != @stack.pop ?? 1 !! 0 }, 'eq' => sub { @stack[*-1] = @stack[*-2] == @stack.pop ?? 1 !! 0 }, 'store' => sub { @data[&value] = @stack.pop }, 'fetch' => sub { @stack.push: @data[&value] // 0 }, 'push' => sub { @stack.push: value() }, 'jmp' => sub { $pc += value() - $w }, 'jz' => sub { $pc += @stack.pop ?? $w !! value() - $w }, 'prts' => sub { print @strings[@stack.pop] }, 'prti' => sub { print @stack.pop }, 'prtc' => sub { print chr @stack.pop }, 'halt' => sub { exit } );   my %op2n = %ops.keys.sort Z=> 0..*; my %n2op = %op2n.invert; %n2op{''} = 'no-op';   for @CODE -> $_ { next unless /\w/; /^ \s* \d+ \s+ (\w+)/ or die "bad line $_"; $memory ~= %op2n{$0}.fmt("%{$w}d"); /'(' ('-'?\d+) ')' | (\d+) ']'? $/; $memory ~= $0 ?? $0.fmt("%{$w}d") !! ' ' x $w; }   loop { my $opcode = substr($memory, $pc, $w).trim; $pc += $w; %ops{%n2op{ $opcode }}(); }
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#Scala
Scala
  package xyz.hyperreal.rosettacodeCompiler   import scala.collection.mutable.{ArrayBuffer, HashMap} import scala.io.Source   object CodeGenerator {   def fromStdin = fromSource(Source.stdin)   def fromString(src: String) = fromSource(Source.fromString(src))   def fromSource(ast: Source) = { val vars = new HashMap[String, Int] val strings = new ArrayBuffer[String] val code = new ArrayBuffer[String] var s: Stream[String] = ast.getLines.toStream   def line = if (s.nonEmpty) { val n = s.head   s = s.tail   n.split(" +", 2) match { case Array(n) => n case a => a } } else sys.error("unexpected end of AST")   def variableIndex(name: String) = vars get name match { case None => val idx = vars.size   vars(name) = idx idx case Some(idx) => idx }   def stringIndex(s: String) = strings indexOf s match { case -1 => val idx = strings.length   strings += s idx case idx => idx }   var loc = 0   def addSimple(inst: String) = { code += f"$loc%4d $inst" loc += 1 }   def addOperand(inst: String, operand: String) = { code += f"$loc%4d $inst%-5s $operand" loc += 5 }   def fixup(inst: String, idx: Int, at: Int) = code(idx) = f"$at%4d $inst%-5s (${loc - at - 1}) $loc"   generate addSimple("halt") println(s"Datasize: ${vars.size} Strings: ${strings.length}")   for (s <- strings) println(s)   println(code mkString "\n")   def generate: Unit = line match { case "Sequence" => generate generate case ";" => case "Assign" => val idx = line match { case Array("Identifier", name: String) => variableIndex(name) case l => sys.error(s"expected identifier: $l") }   generate addOperand("store", s"[$idx]") case Array("Identifier", name: String) => addOperand("fetch", s"[${variableIndex(name)}]") case Array("Integer", n: String) => addOperand("push", s"$n") case Array("String", s: String) => addOperand("push", s"${stringIndex(s)}") case "If" => generate   val cond = loc val condidx = code.length   addOperand("", "") s = s.tail generate   if (s.head == ";") { s = s.tail fixup("jz", condidx, cond) } else { val jump = loc val jumpidx = code.length   addOperand("", "") fixup("jz", condidx, cond) generate fixup("jmp", jumpidx, jump) } case "While" => val start = loc   generate   val cond = loc val condidx = code.length   addOperand("", "") generate addOperand("jmp", s"(${start - loc - 1}) $start") fixup("jz", condidx, cond) case op => generate generate addSimple( op match { case "Prti" => "prti" case "Prts" => "prts" case "Prtc" => "prtc" case "Add" => "add" case "Subtract" => "sub" case "Multiply" => "mul" case "Divide" => "div" case "Mod" => "mod" case "Less" => "lt" case "LessEqual" => "le" case "Greater" => "gt" case "GreaterEqual" => "ge" case "Equal" => "eq" case "NotEqual" => "ne" case "And" => "and" case "Or" => "or" case "Negate" => "neg" case "Not" => "not" } ) } }   }  
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#REXX
REXX
/* REXX */ list = '"abcd","123456789","abcdef","1234567"' Do i=1 By 1 While list>'' Parse Var list s.i ',' list s.i=strip(s.i,,'"') End n=i-1 Do While n>1 max=0 Do i=1 To n If length(s.i)>max Then Do k=i max=length(s.i) End End Call o s.k If k<n Then s.k=s.n n=n-1 End Call o s.1 Exit o: Say length(arg(1)) arg(1) Return
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ring
Ring
  see "working..." + nl   list = ["abcd","123456789"] if len(list[1]) > len(list[2]) first = list[1] second = list[2] else first = list[2] second = list[1] ok   see "Compare length of two strings:" + nl see "" + first + " len = " + len(first) + nl + second + " len = " + len(second) + nl see "done..." + nl  
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.
#Emacs_Lisp
Emacs Lisp
#!/usr/bin/env emacs -script ;; -*- lexical-binding: t -*- ;; run: ./conways-life conways-life.config (require 'cl-lib)   (defconst blinker '("***")) (defconst toad '(".***" "***.")) (defconst pentomino-p '(".**" ".**" ".*.")) (defconst pi-heptomino '("***" "*.*" "*.*")) (defconst glider '(".*." "..*" "***")) (defconst pre-pulsar '("***...***" "*.*...*.*" "***...***")) (defconst ship '("**." "*.*" ".**")) (defconst pentadecathalon '("**********")) (defconst clock '("..*." "*.*." ".*.*" ".*.."))   (defmacro swap (a b) `(setq ,b (prog1 ,a (setq ,a ,b))))   (cl-defstruct world rows cols data)   (defun new-world (rows cols) (make-world :rows rows :cols cols :data (make-vector (* rows cols) nil)))   (defmacro world-pt (w r c) `(+ (* (mod ,r (world-rows ,w)) (world-cols ,w)) (mod ,c (world-cols ,w))))   (defmacro world-ref (w r c) `(aref (world-data ,w) (world-pt ,w ,r ,c)))   (defun print-world (world) (dotimes (r (world-rows world)) (dotimes (c (world-cols world)) (princ (format "%c" (if (world-ref world r c) ?* ?.)))) (terpri)))   (defun insert-pattern (world row col shape) (let ((r row) (c col)) (unless (listp shape) (setq shape (symbol-value shape))) (dolist (row-data shape) (dolist (col-data (mapcar 'identity row-data)) (setf (world-ref world r c) (not (or (eq col-data ?.)))) (setq c (1+ c))) (setq r (1+ r)) (setq c col))))   (defun neighbors (world row col) (let ((n 0)) (dolist (offset '((1 . 1) (1 . 0) (1 . -1) (0 . 1) (0 . -1) (-1 . 1) (-1 . 0) (-1 . -1))) (when (world-ref world (+ row (car offset)) (+ col (cdr offset))) (setq n (1+ n)))) n))   (defun advance-generation (old new) (dotimes (r (world-rows old)) (dotimes (c (world-cols old)) (let ((n (neighbors old r c))) (setf (world-ref new r c) (if (world-ref old r c) (or (= n 2) (= n 3)) (= n 3)))))))   (defun read-config (file-name) (with-temp-buffer (insert-file-contents-literally file-name) (read (current-buffer))))   (defun get-config (key config) (let ((val (assoc key config))) (if (null val) (error (format "missing value for %s" key)) (cdr val))))   (defun insert-patterns (world patterns) (dolist (p patterns) (apply 'insert-pattern (cons world p))))   (defun simulate-life (file-name) (let* ((config (read-config file-name)) (rows (get-config 'rows config)) (cols (get-config 'cols config)) (generations (get-config 'generations config)) (a (new-world rows cols)) (b (new-world rows cols))) (insert-patterns a (get-config 'patterns config)) (dotimes (g generations) (princ (format "generation %d\n" g)) (print-world a) (advance-generation a b) (swap a b))))   (simulate-life (elt command-line-args-left 0))
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#TXR
TXR
(defstruct point nil (x 0) (y 0))
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#UNIX_Shell
UNIX Shell
typeset -T Point=( typeset x typeset y ) Point p p.x=1 p.y=2 echo $p echo ${p.x} ${p.y} Point q=(x=3 y=4) echo ${q.x} ${q.y}
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.
#BQN
BQN
If ← {𝕏⍟𝕎@}´ # Also Repeat IfElse ← {c‿T‿F: c◶F‿T@} While ← {𝕩{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}𝕨@}´ # While 1‿{... to run forever DoWhile ← {𝕏@ ⋄ While 𝕨‿𝕩}´ For ← {I‿C‿P‿A: I@ ⋄ While⟨C,P∘A⟩}   # Switch/case statements have many variations; these are a few Match ← {𝕏𝕨}´ Select ← {(⊑𝕩)◶(1↓𝕩)@} Switch ← {c←⊑𝕩 ⋄ m‿a←<˘⍉∘‿2⥊1↓𝕩 ⋄ (⊑a⊐C)◶m@} Test ← {fn←{C‿A𝕊e:C◶A‿E}´𝕩⋄Fn@}
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
#Go
Go
package cmp   func AllEqual(strings []string) bool { for _, s := range strings { if s != strings[0] { return false } } return true }   func AllLessThan(strings []string) bool { for i := 1; i < len(strings); i++ { if !(strings[i - 1] < s) { return false } } return true }
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Gosu
Gosu
var list = {"a", "b", "c", "d"}   var isHomogeneous = list.toSet().Count < 2 var isOrderedSet = list.toSet().order().toList() == list
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.
#C.2B.2B
C++
#include <iostream>   template<class T> void quibble(std::ostream& o, T i, T e) { o << "{"; if (e != i) { T n = i++; const char* more = ""; while (e != i) { o << more << *n; more = ", "; n = i++; } o << (*more?" and ":"") << *n; } o << "}"; }   int main(int argc, char** argv) { char const* a[] = {"ABC","DEF","G","H"}; for (int i=0; i<5; i++) { quibble(std::cout, a, a+i); std::cout << std::endl; } return 0; }
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
#Crystal
Crystal
possible_doughnuts = ["iced", "jam", "plain"].repeated_combinations(2) puts "There are #{possible_doughnuts.size} possible doughnuts:" possible_doughnuts.each{|doughnut_combi| puts doughnut_combi.join(" and ")}   # Extra credit possible_doughnuts = (1..10).to_a.repeated_combinations(3) # size returns the size of the enumerator, or nil if it can’t be calculated lazily. puts "", "#{possible_doughnuts.size} ways to order 3 donuts given 10 types."
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
#D
D
import std.stdio, std.range;   const struct CombRep { immutable uint nt, nc; private const ulong[] combVal;   this(in uint numType, in uint numChoice) pure nothrow @safe in { assert(0 < numType && numType + numChoice <= 64, "Valid only for nt + nc <= 64 (ulong bit size)"); } body { nt = numType; nc = numChoice; if (nc == 0) return; ulong v = (1UL << (nt - 1)) - 1;   // Init to smallest number that has nt-1 bit set // a set bit is metaphored as a _type_ seperator. immutable limit = v << nc;   ulong[] localCombVal; // Limit is the largest nt-1 bit set number that has nc // zero-bit a zero-bit means a _choice_ between _type_ // seperators. while (v <= limit) { localCombVal ~= v; if (v == 0) break; // Get next nt-1 bit number. immutable t = (v | (v - 1)) + 1; v = t | ((((t & -t) / (v & -v)) >> 1) - 1); } this.combVal = localCombVal; }   uint length() @property const pure nothrow @safe { return combVal.length; }   uint[] opIndex(in uint idx) const pure nothrow @safe { return val2set(combVal[idx]); }   int opApply(immutable int delegate(in ref uint[]) pure nothrow @safe dg) pure nothrow @safe { foreach (immutable v; combVal) { auto set = val2set(v); if (dg(set)) break; } return 1; }   private uint[] val2set(in ulong v) const pure nothrow @safe { // Convert bit pattern to selection set immutable uint bitLimit = nt + nc - 1; uint typeIdx = 0; uint[] set; foreach (immutable bitNum; 0 .. bitLimit) if (v & (1 << (bitLimit - bitNum - 1))) typeIdx++; else set ~= typeIdx; return set; } }   // For finite Random Access Range. auto combRep(R)(R types, in uint numChoice) /*pure*/ nothrow @safe if (hasLength!R && isRandomAccessRange!R) { ElementType!R[][] result;   foreach (const s; CombRep(types.length, numChoice)) { ElementType!R[] r; foreach (immutable i; s) r ~= types[i]; result ~= r; }   return result; }   void main() @safe { foreach (const e; combRep(["iced", "jam", "plain"], 2)) writefln("%-(%5s %)", e); writeln("Ways to select 3 from 10 types is ", CombRep(10, 3).length); }
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#J
J
C=: ! P=: (%&!&x:~ * <:)"0
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Java
Java
  import java.math.BigInteger;   public class CombinationsAndPermutations {   public static void main(String[] args) { System.out.println(Double.MAX_VALUE); System.out.println("A sample of permutations from 1 to 12 with exact Integer arithmetic:"); for ( int n = 1 ; n <= 12 ; n++ ) { int k = n / 2; System.out.printf("%d P %d = %s%n", n, k, permutation(n, k)); }   System.out.println(); System.out.println("A sample of combinations from 10 to 60 with exact Integer arithmetic:"); for ( int n = 10 ; n <= 60 ; n += 5 ) { int k = n / 2; System.out.printf("%d C %d = %s%n", n, k, combination(n, k)); }   System.out.println(); System.out.println("A sample of permutations from 5 to 15000 displayed in floating point arithmetic:"); System.out.printf("%d P %d = %s%n", 5, 2, display(permutation(5, 2), 50)); for ( int n = 1000 ; n <= 15000 ; n += 1000 ) { int k = n / 2; System.out.printf("%d P %d = %s%n", n, k, display(permutation(n, k), 50)); }   System.out.println(); System.out.println("A sample of combinations from 100 to 1000 displayed in floating point arithmetic:"); for ( int n = 100 ; n <= 1000 ; n += 100 ) { int k = n / 2; System.out.printf("%d C %d = %s%n", n, k, display(combination(n, k), 50)); }   }   private static String display(BigInteger val, int precision) { String s = val.toString(); precision = Math.min(precision, s.length()); StringBuilder sb = new StringBuilder(); sb.append(s.substring(0, 1)); sb.append("."); sb.append(s.substring(1, precision)); sb.append(" * 10^"); sb.append(s.length()-1); return sb.toString(); }   public static BigInteger combination(int n, int k) { // Select value with smallest intermediate results // combination(n, k) = combination(n, n-k) if ( n-k < k ) { k = n-k; } BigInteger result = permutation(n, k); while ( k > 0 ) { result = result.divide(BigInteger.valueOf(k)); k--; } return result; }   public static BigInteger permutation(int n, int k) { BigInteger result = BigInteger.ONE; for ( int i = n ; i >= n-k+1 ; i-- ) { result = result.multiply(BigInteger.valueOf(i)); } return result; }   }  
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
#Flex
Flex
%{ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <limits.h>   #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))   typedef enum { tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, tk_Integer, tk_String } TokenType;   void yyerror(char msg[]) { printf(msg); exit(1); }   static int yynval;   struct yylloc { int first_line, first_col; int last_line, last_col; } yylloc;   static void update_loc() { static int curr_line = 1; static int curr_col = 1;   yylloc.first_line = curr_line; yylloc.first_col = curr_col;   {char *s; for (s = yytext; *s != '\0'; s++) { if (*s == '\n') { curr_line++; curr_col = 1; } else { curr_col++; } }}   yylloc.last_line = curr_line; yylloc.last_col = curr_col-1; }   #define YY_USER_ACTION update_loc();   static int kwd_cmp(const void *p1, const void *p2) { return strcmp(*(char **)p1, *(char **)p2); }   static TokenType get_ident_type(const char *ident) { static struct { char *s; TokenType sym; } kwds[] = { {"else", tk_Else}, {"if", tk_If}, {"print", tk_Print}, {"putc", tk_Putc}, {"while", tk_While}, }, *kwp;   return (kwp = bsearch(&ident, kwds, NELEMS(kwds), sizeof(kwds[0]), kwd_cmp)) == NULL ? tk_Ident : kwp->sym; }   %}   %start COMMENT2   %option noyywrap   digit [0-9] ident [a-zA-Z_][a-zA-Z_0-9]*   number {digit}+ string \"[^"\n]*\" char_const \'([^'\n]|\\n|\\\\)\'   %%   <COMMENT2>[^*]+  ; <COMMENT2>\*[^/] ; <COMMENT2>\*\/ BEGIN 0; /* end comment */ "/*" BEGIN COMMENT2;   "{" {return tk_Lbrace;} "}" {return tk_Rbrace;} "(" {return tk_Lparen;} ")" {return tk_Rparen;} "*" {return tk_Mul;} "/" {return tk_Div;} "%" {return tk_Mod;} "+" {return tk_Add;} "-" {return tk_Sub;} "<" {return tk_Lss;} ">" {return tk_Gtr;} "<=" {return tk_Leq;} ">=" {return tk_Geq;} "!=" {return tk_Neq;} "!" {return tk_Not;} "&&" {return tk_And;} "||" {return tk_Or;} ";" {return tk_Semi;} "," {return tk_Comma;} "==" {return tk_Eq;} "=" {return tk_Assign;} {ident} {return get_ident_type(yytext);} {string} {return tk_String;}   [ \t\n]+ ; /* ignore whitespace */   {number} { yynval = strtol(yytext, NULL, 0); if (yynval == LONG_MAX && errno == ERANGE) yyerror("Number exceeds maximum value");   return tk_Integer; }   {char_const} { int n = yytext[1]; char *p = yytext;   if (yyleng < 3) yyerror("empty character constant"); ++p; if (p[0] == '\\') { ++p; if (p[0] == 'n') n = 10; else if (p[0] == '\\') n = '\\'; else yyerror("unknown escape sequence"); } yynval = n; return tk_Integer; }   . yyerror("Unknown character\n");   %%   int main(int argc, char *argv[]) { int tok;   ++argv, --argc; /* skip over program name */ yyin = stdin; if (argc > 0) yyin = fopen(argv[0], "r");   do { tok = yylex(); printf("%5d  %5d %.15s", yylloc.first_line, yylloc.first_col, &"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 " [tok * 16]);   if (tok == tk_Integer) printf("  %5d", yynval); else if (tok == tk_Ident) printf("  %s", yytext); else if (tok == tk_String) printf("  %s", yytext); printf("\n"); } while (tok != tk_EOI); return 0; }
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"
#DCL
DCL
$ i = 1 $ loop: $ write sys$output "the value of P''i' is ", p'i $ i = i + 1 $ if i .le. 8 then $ goto loop
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"
#Delphi
Delphi
// The program name and the directory it was called from are in // param[0] , so given the axample of myprogram -c "alpha beta" -h "gamma"   for x := 0 to paramcount do writeln('param[',x,'] = ',param[x]);   // will yield ( assuming windows and the c drive as the only drive) :   // param[0] = c:\myprogram // param[1] = -c // param[2] = alpha beta // param[3] = -h // param[4] = gamma  
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.)
#BASIC
BASIC
100 REM Standard BASIC comments begin with "REM" (remark) and extend to the end of the line 110 PRINT "this is code": REM comment after statement
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.)
#Batch_File
Batch File
rem Single-line comment.
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#RATFOR
RATFOR
###################################################################### # # The Rosetta Code code virtual machine in Ratfor 77. # # The implementation assumes your FORTRAN compiler supports 1-byte # INTEGER*1 and 4-byte INTEGER*4. Integer storage will be # native-endian, achieved via EQUIVALENCE. (GNU Fortran and f2c both # should work.) # # # 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 vm-in-ratfor.r > vm-in-ratfor.f # f2c -C -Nc40 vm-in-ratfor.f # cc vm-in-ratfor.c -lf2c # ./a.out < compiler-tests/primes.vm # # With gfortran, a little differently: # # ratfor77 vm-in-ratfor.r > vm-in-ratfor.f # gfortran -fcheck=all -std=legacy vm-in-ratfor.f # ./a.out < compiler-tests/primes.vm # # # 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 wish to modify.   define(LINESZ, 256) # Size of an input line. define(OUTLSZ, 1024) # Size of an output line. define(STRNSZ, 4096) # Size of the string pool. define(STCKSZ, 4096) # Size of stacks. define(MAXVAR, 256) # Maximum number of variables. define(MAXSTR, 256) # Maximum number of strings. define(CODESZ, 16384) # Maximum size of a compiled program.   define(STRSZ, 2) # Size of an entry in the VM strings array. define(STRI, 1) # Index of the string within strngs. define(STRN, 2) # Length of the string.   #---------------------------------------------------------------------   define(NEWLIN, 10) # The Unix newline character (ASCII LF). define(DQUOTE, 34) # The double quote character. define(BACKSL, 92) # The backslash character.   #---------------------------------------------------------------------   define(OPHALT, 1) define(OPADD, 2) define(OPSUB, 3) define(OPMUL, 4) define(OPDIV, 5) define(OPMOD, 6) define(OPLT, 7) define(OPGT, 8) define(OPLE, 9) define(OPGE, 10) define(OPEQ, 11) define(OPNE, 12) define(OPAND, 13) define(OPOR, 14) define(OPNEG, 15) define(OPNOT, 16) define(OPPRTC, 17) define(OPPRTI, 18) define(OPPRTS, 19) define(OPFTCH, 20) define(OPSTOR, 21) define(OPPUSH, 22) define(OPJMP, 23) define(OPJZ, 24)   #---------------------------------------------------------------------   function issp (c)   # Is a character a space character?   implicit none   character c logical issp   integer ic   ic = ichar (c) issp = (ic == 32 || (9 <= ic && ic <= 13)) end   function 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 isdgt (c)   # Is c character code for a digit?   implicit none   integer c logical isdgt   isdgt = (ichar ('0') <= c && c <= ichar ('9')) end   function skipsp (str, i, imax)   # Skip past spaces in a string.   implicit none   character str(*) integer i integer imax integer skipsp   logical issp   logical done   skipsp = i done = .false. while (!done) { if (imax <= skipsp) done = .true. else if (!issp (str(skipsp))) done = .true. else skipsp = skipsp + 1 } end   function skipns (str, i, imax)   # Skip past non-spaces in a string.   implicit none   character str(*) integer i integer imax integer skipns   logical issp   logical done   skipns = i done = .false. while (!done) { if (imax <= skipns) done = .true. else if (issp (str(skipns))) done = .true. else skipns = skipns + 1 } end   function trimrt (str, n)   # Find the length of a string, if one ignores trailing spaces.   implicit none   character str(*) integer n integer trimrt   logical issp   logical done   trimrt = n done = .false. while (!done) { if (trimrt == 0) done = .true. else if (!issp (str(trimrt))) done = .true. else trimrt = trimrt - 1 } end   function skipal (str, i, imax)   # Skip past alphabetic characters in a string.   implicit none   character str(*) integer i integer imax integer skipal   logical isalph   logical done   skipal = i done = .false. while (!done) { if (imax <= skipal) done = .true. else if (!isalph (ichar (str(skipal)))) done = .true. else skipal = skipal + 1 } end   function skipdg (str, i, imax)   # Skip past digits in a string.   implicit none   character str(*) integer i integer imax integer skipdg   logical isdgt   logical done   skipdg = i done = .false. while (!done) { if (imax <= skipdg) done = .true. else if (!isdgt (ichar (str(skipdg)))) done = .true. else skipdg = skipdg + 1 } end   function skipnd (str, i, imax)   # Skip past nondigits in a string.   implicit none   character str(*) integer i integer imax integer skipnd   logical isdgt   logical done   skipnd = i done = .false. while (!done) { if (imax <= skipnd) done = .true. else if (isdgt (ichar (str(skipnd)))) done = .true. else skipnd = skipnd + 1 } end   function skipd1 (str, i, imax)   # Skip past digits and '-' in a string.   implicit none   character str(*) integer i integer imax integer skipd1   logical isdgt   logical done   skipd1 = i done = .false. while (!done) { if (imax <= skipd1) done = .true. else if (!isdgt (ichar (str(skipd1))) && str(skipd1) != '-') done = .true. else skipd1 = skipd1 + 1 } end   function skipn1 (str, i, imax)   # Skip past nondigits in a string, except '-'.   implicit none   character str(*) integer i integer imax integer skipn1   logical isdgt   logical done   skipn1 = i done = .false. while (!done) { if (imax <= skipn1) done = .true. else if (isdgt (ichar (str(skipn1))) || str(skipn1) == '-') done = .true. else skipn1 = skipn1 + 1 } end   function tolowr (c)   implicit none   character c character tolowr   integer ic   # The following is correct for ASCII, and will work with Unicode # code points, but is incorrect for EBCDIC.   ic = ichar (c) if (ichar ('A') <= ic && ic <= ichar ('Z')) ic = ic - ichar('A') + ichar('a') tolowr = char (ic) end   #---------------------------------------------------------------------   subroutine addstq (strngs, istrng, src, i0, n0, i, n)   # Add a quoted 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 logical done   1000 format ('attempt to treat an unquoted string as a quoted string')   if (src(i0) != char (DQUOTE) || src(i0 + n0 - 1) != char (DQUOTE)) { write (*, 1000) stop }   i = istrng   n = 0 j = i0 + 1 done = .false. while (j != i0 + n0 - 1) if (i == STRNSZ) { write (*, '(''string pool exhausted'')') stop } else if (src(j) == char (BACKSL)) { if (j == i0 + n0 - 1) { write (*, '(''incorrectly formed quoted string'')') stop } if (src(j + 1) == 'n') strngs(istrng) = char (NEWLIN) else if (src(j + 1) == char (BACKSL)) strngs(istrng) = src(j + 1) else { write (*, '(''unrecognized escape sequence'')') stop } istrng = istrng + 1 n = n + 1 j = j + 2 } else { strngs(istrng) = src(j) istrng = istrng + 1 n = n + 1 j = j + 1 } end   #---------------------------------------------------------------------   subroutine push (stack, sp, i)   implicit none   integer stack(STCKSZ) integer sp # Stack pointer. integer i # Value to push.   if (sp == STCKSZ) { write (*, '(''stack overflow in push'')') stop } stack(sp) = i sp = sp + 1 end   function pop (stack, sp)   implicit none   integer stack(STCKSZ) integer sp # Stack pointer. integer pop   if (sp == 1) { write (*, '(''stack underflow in pop'')') stop } sp = sp - 1 pop = stack(sp) end   function nstack (sp)   implicit none   integer sp # Stack pointer. integer nstack   nstack = sp - 1 # Current cardinality of the stack. end   #---------------------------------------------------------------------   subroutine flushl (outbuf, noutbf)   # Flush a line from the output buffer.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf.   character*20 fmt integer i   if (noutbf == 0) write (*, '()') else { write (fmt, 1000) noutbf 1000 format ('(', I10, 'A)') write (*, fmt) (outbuf(i), i = 1, noutbf) noutbf = 0 } end   subroutine wrtchr (outbuf, noutbf, ch)   # Write a character to output.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. character ch # The character to output.   # This routine silently truncates anything that goes past the buffer # boundary.   if (ch == char (NEWLIN)) call flushl (outbuf, noutbf) else if (noutbf < OUTLSZ) { noutbf = noutbf + 1 outbuf(noutbf) = ch } end   subroutine wrtstr (outbuf, noutbf, str, i, n)   # Write a substring to output.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. character str(*) # The string from which to output. integer i, n # Index and length of the substring.   integer j   for (j = 0; j < n; j = j + 1) call wrtchr (outbuf, noutbf, str(i + j)) end   subroutine wrtint (outbuf, noutbf, ival, colcnt)   # Write an integer to output.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. integer ival # The non-negative integer to print. integer colcnt # Column count, or zero for free format.   integer skipsp   character*40 buf integer i, j   write (buf, '(I40)') ival i = skipsp (buf, 1, 41) if (0 < colcnt) for (j = 1; j < colcnt - (40 - i); j = j + 1) call wrtchr (outbuf, noutbf, ' ') while (i <= 40) { call wrtchr (outbuf, noutbf, buf(i:i)) i = i + 1 } end   #---------------------------------------------------------------------   function strnat (str, i, n)   # Convert a string to a non-negative integer.   implicit none   character str(*) integer i, n integer strnat   integer j   strnat = 0 for (j = 0; j < n; j = j + 1) strnat = (10 * strnat) + (ichar (str(i + j)) - ichar ('0')) end   function strint (str, i, n)   # Convert a string to an integer   implicit none   character str(*) integer i, n integer strint   integer strnat   if (str(i) == '-') strint = -strnat (str, i + 1, n - 1) else strint = strnat (str, i, n) end   #---------------------------------------------------------------------   subroutine put1 (code, i, opcode)   # Store a 1-byte operation.   implicit none   integer*1 code(0 : CODESZ - 1) # Byte code. integer i # Address to put the code at. integer*1 opcode   if (CODESZ - i < 1) { write (*, '(''address beyond the size of memory'')') stop } code(i) = opcode end   subroutine put5 (code, i, opcode, ival)   # Store a 5-byte operation.   implicit none   integer*1 code(0 : CODESZ - 1) # Byte code. integer i # Address to put the code at. integer*1 opcode # integer ival # Immediate integer value.   integer*4 ival32 integer*1 ival8(4) equivalence (ival32, ival8)   if (CODESZ - i < 5) { write (*, '(''address beyond the size of memory'')') stop } code(i) = opcode   # Native-endian storage. ival32 = ival code(i + 1) = ival8(1) code(i + 2) = ival8(2) code(i + 3) = ival8(3) code(i + 4) = ival8(4) end   function getimm (code, i)   # Get an immediate value from the code, at address i.   implicit none   integer*1 code(0 : CODESZ - 1) # Byte code. integer i # Address at which the integer resides. integer getimm # Immediate integer value.   integer*4 ival32 integer*1 ival8(4) equivalence (ival32, ival8)   if (i < 0 || CODESZ <= i + 3) { write (*, '(''code address out of range'')') stop }   # Native-endian storage. ival8(1) = code(i) ival8(2) = code(i + 1) ival8(3) = code(i + 2) ival8(4) = code(i + 3) getimm = ival32 end   #---------------------------------------------------------------------   subroutine rdhead (datsiz, strsiz)   # Read the header line.   implicit none   integer datsiz integer strsiz   integer skipnd integer skipdg integer strnat   character line(LINESZ) character*20 fmt integer i1, j1, i2, j2   # Read a line of text as an array of characters. write (fmt, '(''('', I10, ''A)'')') LINESZ read (*, fmt) line   i1 = skipnd (line, 1, LINESZ + 1) j1 = skipdg (line, i1, LINESZ + 1) i2 = skipnd (line, j1, LINESZ + 1) j2 = skipdg (line, i2, LINESZ + 1) if (i1 == j1 || i2 == j2) { write (*, '(''bad header line'')') stop } datsiz = strnat (line, i1, j1 - i1) strsiz = strnat (line, i2, j2 - i2) end   subroutine rdstrs (strs, strsiz, strngs, istrng)   implicit none   integer strs(1:STRSZ, 0 : MAXSTR - 1) integer strsiz character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot.   integer trimrt integer skipsp   character line(LINESZ) character*20 fmt integer j integer i, n integer i0, n0   # Read lines of text as an array of characters. write (fmt, '(''('', I10, ''A)'')') LINESZ   for (j = 0; j < strsiz; j = j + 1) { read (*, fmt) line n0 = trimrt (line, LINESZ) i0 = skipsp (line, 1, n0 + 1) if (i0 == n0 + 1) { write (*, '(''blank line where a string should be'')') stop } call addstq (strngs, istrng, line, i0, n0 - i0 + 1, i, n) strs(STRI, j) = i strs(STRN, j) = n } end   function stropc (str, i, n)   # Convert substring to an opcode.   implicit none   character str(*) integer i, n integer*1 stropc   stropc = -1 if (n == 2) { if (str(i) == 'l') { if (str(i + 1) == 't') stropc = OPLT else if (str(i + 1) == 'e') stropc = OPLE } else if (str(i) == 'g') { if (str(i + 1) == 't') stropc = OPGT else if (str(i + 1) == 'e') stropc = OPGE } else if (str(i) == 'e' && str(i + 1) == 'q') stropc = OPEQ else if (str(i) == 'n' && str(i + 1) == 'e') stropc = OPNE else if (str(i) == 'o' && str(i + 1) == 'r') stropc = OPOR else if (str(i) == 'j' && str(i + 1) == 'z') stropc = OPJZ } else if (n == 3) { if (str(i) == 'a') { if (str(i + 1) == 'd' && str(i + 2) == 'd') stropc = OPADD else if (str(i + 1) == 'n' && str(i + 2) == 'd') stropc = OPAND } else if (str(i) == 'm') { if (str(i + 1) == 'o' && str(i + 2) == 'd') stropc = OPMOD else if (str(i + 1) == 'u' && str(i + 2) == 'l') stropc = OPMUL } else if (str(i) == 'n') { if (str(i + 1) == 'e' && str(i + 2) == 'g') stropc = OPNEG else if (str(i + 1) == 'o' && str(i + 2) == 't') stropc = OPNOT } else if (str(i) == 's' && str(i + 1) == 'u' _ && str(i + 2) == 'b') stropc = OPSUB else if (str(i) == 'd' && str(i + 1) == 'i' _ && str(i + 2) == 'v') stropc = OPDIV else if (str(i) == 'j' && str(i + 1) == 'm' _ && str(i + 2) == 'p') stropc = OPJMP } else if (n == 4) { if (str(i) == 'p') { if (str(i + 1) == 'r' && str(i + 2) == 't') { if (str(i + 3) == 'c') stropc = OPPRTC else if (str(i + 3) == 'i') stropc = OPPRTI else if (str(i + 3) == 's') stropc = OPPRTS } if (str(i + 1) == 'u' && str(i + 2) == 's' _ && str(i + 3) == 'h') stropc = OPPUSH } else if (str(i) == 'h' && str(i + 1) == 'a' _ && str(i + 2) == 'l' && str(i + 3) == 't') stropc = OPHALT } else if (n == 5) { if (str(i) == 'f' && str(i + 1) == 'e' && str(i + 2) == 't' _ && str(i + 3) == 'c' && str(i + 4) == 'h') stropc = OPFTCH if (str(i) == 's' && str(i + 1) == 't' && str(i + 2) == 'o' _ && str(i + 3) == 'r' && str(i + 4) == 'e') stropc = OPSTOR } if (stropc == -1) { write (*, '(''unrecognized opcode name'')') stop } end   subroutine rdops (code)   # Read the opcodes and their immediate values.   implicit none   integer*1 code(0 : CODESZ - 1) # The byte code.   integer trimrt integer skipsp integer skipal integer skipdg integer skipd1 integer skipn1 integer strnat integer strint integer*1 stropc character tolowr   character line(LINESZ) character*20 fmt integer stat integer n integer j integer iaddr, jaddr # Address index and size. integer iopnm, jopnm # Opcode name index and size. integer iarg, jarg integer addr integer arg integer*1 opcode   # Read lines of text as an array of characters. write (fmt, '(''('', I10, ''A)'')') LINESZ   read (*, fmt, iostat = stat) line while (stat == 0) { n = trimrt (line, LINESZ)   for (j = 1; j <= n; j = j + 1) line(j) = tolowr (line(j))   iaddr = skipsp (line, 1, n + 1) jaddr = skipdg (line, iaddr, n + 1) addr = strnat (line, iaddr, jaddr - iaddr)   iopnm = skipsp (line, jaddr, n + 1) jopnm = skipal (line, iopnm, n + 1) opcode = stropc (line, iopnm, jopnm - iopnm)   if (opcode == OPPUSH || opcode == OPFTCH || opcode == OPSTOR _ || opcode == OPJMP || opcode == OPJZ) { iarg = skipn1 (line, jopnm, n + 1) jarg = skipd1 (line, iarg, n + 1) arg = strint (line, iarg, jarg - iarg) call put5 (code, addr, opcode, arg) } else call put1 (code, addr, opcode)   read (*, fmt, iostat = stat) line } end   subroutine rdcode (strs, strngs, istrng, code)   # Read and parse the "assembly" code.   implicit none   integer strs(1:STRSZ, 0 : MAXSTR - 1) character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer*1 code(0 : CODESZ - 1) # The byte code.   integer datsiz integer strsiz   call rdhead (datsiz, strsiz) if (MAXVAR < datsiz) { write (*, '(''too many variables'')') stop } if (MAXSTR < strsiz) { write (*, '(''too many strings'')') stop }   call rdstrs (strs, strsiz, strngs, istrng) call rdops (code) end   #---------------------------------------------------------------------   subroutine stkbin (sp)   implicit none   integer sp   if (sp < 3) { write (*, '(''stack underflow in binary operation'')') stop } end   subroutine stkun (sp)   implicit none   integer sp   if (sp < 2) { write (*, '(''stack underflow in unary operation'')') stop } end   function logl2i (b)   implicit none   logical b integer logl2i   if (b) logl2i = 1 else logl2i = 0 end   subroutine rncode (strs, strngs, code, outbuf, noutbf)   # Run the code.   implicit none   integer strs(1:STRSZ, 0 : MAXSTR - 1) character strngs(STRNSZ) # String pool. integer*1 code(0 : CODESZ - 1) # The byte code. character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf.   integer logl2i integer getimm integer pop   integer stack(STCKSZ) integer data(0 : MAXVAR - 1) integer sp # Stack pointer.   integer pc # Program counter. integer ip # Instruction pointer. equivalence (pc, ip) # LOL, use either name. :)   integer i, n integer*1 opcode logical done   sp = 1 ip = 0   done = .false. while (!done) { if (ip < 0 || CODESZ <= ip) { write (*, '(''code address out of range'')') stop } opcode = code(ip) ip = ip + 1 if (opcode == OPADD) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = stack (sp - 1) + stack(sp) } else if (opcode == OPSUB) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = stack (sp - 1) - stack(sp) } else if (opcode == OPMUL) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = stack (sp - 1) * stack(sp) } else if (opcode == OPDIV) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = stack (sp - 1) / stack(sp) } else if (opcode == OPMOD) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = mod (stack (sp - 1), stack(sp)) } else if (opcode == OPLT) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = logl2i (stack (sp - 1) < stack(sp)) } else if (opcode == OPGT) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = logl2i (stack (sp - 1) > stack(sp)) } else if (opcode == OPLE) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = logl2i (stack (sp - 1) <= stack(sp)) } else if (opcode == OPGE) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = logl2i (stack (sp - 1) >= stack(sp)) } else if (opcode == OPEQ) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = logl2i (stack (sp - 1) == stack(sp)) } else if (opcode == OPNE) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = logl2i (stack (sp - 1) != stack(sp)) } else if (opcode == OPAND) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = _ logl2i (stack (sp - 1) != 0 && stack(sp) != 0) } else if (opcode == OPOR) { call stkbin (sp) sp = sp - 1 stack(sp - 1) = _ logl2i (stack (sp - 1) != 0 || stack(sp) != 0) } else if (opcode == OPNEG) { call stkun (sp) stack(sp - 1) = -stack(sp - 1) } else if (opcode == OPNOT) { call stkun (sp) stack(sp - 1) = logl2i (stack(sp - 1) == 0) } else if (opcode == OPPRTC) { call wrtchr (outbuf, noutbf, char (pop (stack, sp))) } else if (opcode == OPPRTI) { call wrtint (outbuf, noutbf, pop (stack, sp), 0) } else if (opcode == OPPRTS) { i = pop (stack, sp) if (i < 0 || MAXSTR <= i) { write (*, '(''string address out of range'')') stop } n = strs(STRN, i) i = strs(STRI, i) call wrtstr (outbuf, noutbf, strngs, i, n) } else if (opcode == OPFTCH) { i = getimm (code, ip) ip = ip + 4 if (i < 0 || MAXVAR <= i) { write (*, '(''data address out of range'')') stop } call push (stack, sp, data(i)) } else if (opcode == OPSTOR) { i = getimm (code, ip) ip = ip + 4 if (i < 0 || MAXVAR <= i) { write (*, '(''data address out of range'')') stop } data(i) = pop (stack, sp) } else if (opcode == OPPUSH) { call push (stack, sp, getimm (code, ip)) ip = ip + 4 } else if (opcode == OPJMP) { ip = ip + getimm (code, ip) } else if (opcode == OPJZ) { if (pop (stack, sp) == 0) ip = ip + getimm (code, ip) else ip = ip + 4 } else { # Halt on OPHALT or any unrecognized code. done = .true. } } end   #---------------------------------------------------------------------   program vm   implicit none   integer strs(1:STRSZ, 0 : MAXSTR - 1) character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer*1 code(0 : CODESZ - 1) # The byte code. character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf.   integer j   istrng = 1 noutbf = 0   for (j = 0; j < CODESZ; j = j + 1) code(j) = OPHALT   call rdcode (strs, strngs, istrng, code) call rncode (strs, strngs, code, outbuf, noutbf)   if (noutbf != 0) call flushl (outbuf, noutbf) end   ######################################################################
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#Scheme
Scheme
  (import (scheme base) (scheme file) (scheme process-context) (scheme write) (only (srfi 1) delete-duplicates list-index) (only (srfi 13) string-delete string-index string-trim))   (define *names* '((Add add) (Subtract sub) (Multiply mul) (Divide div) (Mod mod) (Less lt) (Greater gt) (LessEqual le) (GreaterEqual ge) (Equal eq) (NotEqual ne) (And and) (Or or) (Negate neg) (Not not) (Prts prts) (Prti prti) (Prtc prtc)))   (define (change-name name) (if (assq name *names*) (cdr (assq name *names*)) (error "Cannot find name" name)))   ;; Read AST from given filename ;; - return as an s-expression (define (read-code filename) (define (read-expr) (let ((line (string-trim (read-line)))) (if (string=? line ";") '() (let ((space (string-index line #\space))) (if space (list (string->symbol (string-trim (substring line 0 space))) (string-trim (substring line space (string-length line)))) (list (string->symbol line) (read-expr) (read-expr))))))) ; (with-input-from-file filename (lambda () (read-expr))))   ;; run a three-pass assembler (define (generate-code ast) (define new-address ; create a new unique address - for jump locations (let ((count 0)) (lambda () (set! count (+ 1 count)) (string->symbol (string-append "loc-" (number->string count)))))) ; define some names for fields (define left cadr) (define right (lambda (x) (cadr (cdr x)))) ; (define (extract-values ast) (if (null? ast) (values '() '()) (case (car ast) ((Integer) (values '() '())) ((Negate Not Prtc Prti Prts) (extract-values (left ast))) ((Assign Add Subtract Multiply Divide Mod Less Greater LessEqual GreaterEqual Equal NotEqual And Or If While Sequence) (let-values (((a b) (extract-values (left ast))) ((c d) (extract-values (right ast)))) (values (delete-duplicates (append a c) string=?) (delete-duplicates (append b d) string=?)))) ((String) (values '() (list (left ast)))) ((Identifier) (values (list (left ast)) '()))))) ; (let-values (((constants strings) (extract-values ast))) (define (constant-idx term) (list-index (lambda (s) (string=? s term)) constants)) (define (string-idx term) (list-index (lambda (s) (string=? s term)) strings)) ; (define (pass-1 ast asm) ; translates ast into a list of basic operations (if (null? ast) asm (case (car ast) ((Integer) (cons (list 'push (left ast)) asm)) ((Identifier) (cons (list 'fetch (constant-idx (left ast))) asm)) ((String) (cons (list 'push (string-idx (left ast))) asm)) ((Assign) (cons (list 'store (constant-idx (left (left ast)))) (pass-1 (right ast) asm))) ((Add Subtract Multiply Divide Mod Less Greater LessEqual GreaterEqual Equal NotEqual And Or) ; binary operators (cons (change-name (car ast)) (pass-1 (right ast) (pass-1 (left ast) asm)))) ((Negate Not Prtc Prti Prts) ; unary operations (cons (change-name (car ast)) (pass-1 (left ast) asm))) ((If) (let ((label-else (new-address)) (label-end (new-address))) (if (null? (right (right ast))) (cons (list 'label label-end) ; label for end of if statement (pass-1 (left (right ast)) ; output the 'then block (cons (list 'jz label-end) ; jump to end when test is false (pass-1 (left ast) asm)))) (cons (list 'label label-end) ; label for end of if statement (pass-1 (right (right ast)) ; output the 'else block (cons (list 'label label-else) (cons (list 'jmp label-end) ; jump past 'else, after 'then (pass-1 (left (right ast)) ; output the 'then block (cons (list 'jz label-else) ; jumpt to else when false (pass-1 (left ast) asm)))))))))) ((While) (let ((label-test (new-address)) (label-end (new-address))) (cons (list 'label label-end) ; introduce a label for end of while block (cons (list 'jmp label-test) ; jump back to repeat test (pass-1 (right ast) ; output the block (cons (list 'jz label-end) ; test failed, jump around block (pass-1 (left ast) ; output the test (cons (list 'label label-test) ; introduce a label for test asm)))))))) ((Sequence) (pass-1 (right ast) (pass-1 (left ast) asm))) (else "Unknown token type")))) ; (define (pass-2 asm) ; adds addresses and fills in jump locations (define (fill-addresses) (let ((addr 0)) (map (lambda (instr) (let ((res (cons addr instr))) (unless (eq? (car instr) 'label) (set! addr (+ addr (if (= 1 (length instr)) 1 5)))) res)) asm))) ; (define (extract-labels asm) (let ((labels '())) (for-each (lambda (instr) (when (eq? (cadr instr) 'label) (set! labels (cons (cons (cadr (cdr instr)) (car instr)) labels)))) asm) labels)) ; (define (add-jump-locations asm labels rec) (cond ((null? asm) (reverse rec)) ((eq? (cadr (car asm)) 'label) ; ignore the labels (add-jump-locations (cdr asm) labels rec)) ((memq (cadr (car asm)) '(jmp jz)) ; replace labels with addresses for jumps (add-jump-locations (cdr asm) labels (cons (list (car (car asm)) ; previous address (cadr (car asm)) ; previous jump type (cdr (assq (cadr (cdar asm)) labels))) ; actual address rec))) (else (add-jump-locations (cdr asm) labels (cons (car asm) rec))))) ; (let ((asm+addr (fill-addresses))) (add-jump-locations asm+addr (extract-labels asm+addr) '()))) ; (define (output-instruction instr) (display (number->string (car instr))) (display #\tab) (display (cadr instr)) (display #\tab) (case (cadr instr) ((fetch store) (display "[") (display (number->string (cadr (cdr instr)))) (display "]\n")) ((jmp jz) (display (string-append "(" (number->string (- (cadr (cdr instr)) (car instr) 1)) ")")) (display #\tab) (display (number->string (cadr (cdr instr)))) (newline)) ((push) (display (cadr (cdr instr))) (newline)) (else (newline)))) ; generate the code and output to stdout (display (string-append "Datasize: " (number->string (length constants)) " Strings: " (number->string (length strings)))) (newline) (for-each (lambda (str) (display str) (newline)) strings) (for-each output-instruction (pass-2 (reverse (cons (list 'halt) (pass-1 ast '())))))))   ;; read AST from file and output code to stdout (if (= 2 (length (command-line))) (generate-code (read-code (cadr (command-line)))) (display "Error: pass an ast filename\n"))  
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ruby
Ruby
  a, b = "Given two strings", "of different length" [a,b].sort_by{|s| - s.size }.each{|s| puts s + " (size: #{s.size})"}   list = ["abcd","123456789","abcdef","1234567"] puts list.sort_by{|s|- s.size}  
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Rust
Rust
  fn compare_and_report<T: ToString>(string1: T, string2: T) -> String { let strings = [string1.to_string(), string2.to_string()]; let difference = strings[0].len() as i32 - strings[1].len() as i32; if difference == 0 { // equal format!("\"{}\" and \"{}\" are of equal length, {}", strings[0], strings[1], strings[0].len()) } else if difference > 1 { // string1 > string2 format!("\"{}\" has length {} and is the longest\n\"{}\" has length {} and is the shortest", strings[0], strings[0].len(), strings[1], strings[1].len()) } else { // string2 > string1 format!("\"{}\" has length {} and is the longest\n\"{}\" has length {} and is the shortest", strings[1], strings[1].len(), strings[0], strings[0].len()) } }   fn main() { println!("{}", compare_and_report("a", "b")); println!("\n{}", compare_and_report("cd", "e")); println!("\n{}", compare_and_report("f", "gh")); }  
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.
#Erlang
Erlang
    -module(life).   -export([bang/1]).     -define(CHAR_DEAD, 32). % " " -define(CHAR_ALIVE, 111). % "o" -define(CHAR_BAR, 45). % "-"   -define(GEN_INTERVAL, 100).     -record(state, {x  :: non_neg_integer() ,y  :: non_neg_integer() ,n  :: pos_integer() ,bar  :: nonempty_string() ,board  :: array() ,gen_count  :: pos_integer() ,gen_duration :: non_neg_integer() ,print_time  :: non_neg_integer() }).     %% ============================================================================ %% API %% ============================================================================   bang(Args) -> [X, Y] = [atom_to_integer(A) || A <- Args], {Time, Board} = timer:tc(fun() -> init_board(X, Y) end), State = #state{x = X ,y = Y ,n = X * Y ,bar = [?CHAR_BAR || _ <- lists:seq(1, X)] ,board = Board ,gen_count = 1 % Consider inital state to be generation 1 ,gen_duration = Time ,print_time = 0 % There was no print time yet }, life_loop(State).     %% ============================================================================ %% Internal %% ============================================================================   life_loop( #state{x = X ,y = Y ,n = N ,bar = Bar ,board = Board ,gen_count = GenCount ,gen_duration = Time ,print_time = LastPrintTime }=State) ->   {PrintTime, ok} = timer:tc( fun() -> do_print_screen(Board, Bar, X, Y, N, GenCount, Time, LastPrintTime) end ),   {NewTime, NewBoard} = timer:tc( fun() -> next_generation(X, Y, Board) end ),   NewState = State#state{board = NewBoard ,gen_count = GenCount + 1 ,gen_duration = NewTime ,print_time = PrintTime },   NewTimeMil = NewTime / 1000, NextGenDelay = at_least_zero(round(?GEN_INTERVAL - NewTimeMil)), timer:sleep(NextGenDelay),   life_loop(NewState).     at_least_zero(Integer) when Integer >= 0 -> Integer; at_least_zero(_) -> 0.     do_print_screen(Board, Bar, X, Y, N, GenCount, Time, PrintTime) -> ok = do_print_status(Bar, X, Y, N, GenCount, Time, PrintTime), ok = do_print_board(Board).     do_print_status(Bar, X, Y, N, GenCount, TimeMic, PrintTimeMic) -> TimeSec = TimeMic / 1000000, PrintTimeSec = PrintTimeMic / 1000000, ok = io:format("~s~n", [Bar]), ok = io:format( "X: ~b Y: ~b CELLS: ~b GENERATION: ~b DURATION: ~f PRINT TIME: ~f~n", [X, Y, N, GenCount, TimeSec, PrintTimeSec] ), ok = io:format("~s~n", [Bar]).     do_print_board(Board) -> % It seems that just doing a fold should be faster than map + to_list % combo, but, after measuring several times, map + to_list has been % consistently (nearly twice) faster than either foldl or foldr. RowStrings = array:to_list( array:map( fun(_, Row) -> array:to_list( array:map( fun(_, State) -> state_to_char(State) end, Row ) ) end, Board ) ),   ok = lists:foreach( fun(RowString) -> ok = io:format("~s~n", [RowString]) end, RowStrings ).     state_to_char(0) -> ?CHAR_DEAD; state_to_char(1) -> ?CHAR_ALIVE.     next_generation(W, H, Board) -> array:map( fun(Y, Row) -> array:map( fun(X, State) -> Neighbors = filter_offsides(H, W, neighbors(X, Y)), States = neighbor_states(Board, Neighbors), LiveNeighbors = lists:sum(States), new_state(State, LiveNeighbors) end, Row ) end, Board ).     new_state(1, LiveNeighbors) when LiveNeighbors < 2 -> 0; new_state(1, LiveNeighbors) when LiveNeighbors < 4 -> 1; new_state(1, LiveNeighbors) when LiveNeighbors > 3 -> 0; new_state(0, LiveNeighbors) when LiveNeighbors =:= 3 -> 1; new_state(State, _LiveNeighbors) -> State.     neighbor_states(Board, Neighbors) -> [array:get(X, array:get(Y, Board)) || {X, Y} <- Neighbors].     filter_offsides(H, W, Coordinates) -> [{X, Y} || {X, Y} <- Coordinates, is_onside(X, Y, H, W)].     is_onside(X, Y, H, W) when (X >= 0) and (Y >= 0) and (X < W) and (Y < H) -> true; is_onside(_, _, _, _) -> false.     neighbors(X, Y) -> [{X + OffX, Y + OffY} || {OffX, OffY} <- offsets()].     offsets() -> [offset(D) || D <- directions()].     offset('N') -> { 0, -1}; offset('NE') -> { 1, -1}; offset('E') -> { 1, 0}; offset('SE') -> { 1, 1}; offset('S') -> { 0, 1}; offset('SW') -> {-1, 1}; offset('W') -> {-1, 0}; offset('NW') -> {-1, -1}.     directions() -> ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].     init_board(X, Y) -> array:map(fun(_, _) -> init_row(X) end, array:new(Y)).     init_row(X) -> array:map(fun(_, _) -> init_cell_state() end, array:new(X)).     init_cell_state() -> crypto:rand_uniform(0, 2).     atom_to_integer(Atom) -> list_to_integer(atom_to_list(Atom)).    
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Ursala
Ursala
point :: x y
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Vala
Vala
struct Point { int x; int y; }
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.
#Bracmat
Bracmat
2+2:5 & put$"Strange, must check that Bracmat interpreter." & 0 | put$"That's what I thought." & Right
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
#Haskell
Haskell
allEqual :: Eq a => [a] -> Bool allEqual xs = and $ zipWith (==) xs (tail xs)   allIncr :: Ord a => [a] -> Bool allIncr xs = and $ zipWith (<) xs (tail xs)
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
#Icon_and_Unicon
Icon and Unicon
# # list-compare.icn # link fullimag   procedure main() L1 := ["aa"] L2 := ["aa", "aa", "aa"] L3 := ["", "aa", "ab", "ac"] L4 := ["aa", "bb", "cc"] L5 := ["cc", "bb", "aa"]   every L := (L1 | L2 | L3 | L4 | L5) do { writes(fullimage(L)) writes(": equal ") writes(if allequal(L) then "true" else "false") writes(", ascending ") write(if ascending(L) then "true" else "false") } end   # test for all identical procedure allequal(L) if *L < 2 then return a := L[1] every b := L[2 to *L] do { if a ~== b then fail a := b } return end   # test for strictly ascending procedure ascending(L) if *L < 2 then return a := L[1] every b := L[2 to *L] do { if a >>= b then fail a := b } return end
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#Clojure
Clojure
(defn quibble [sq] (let [sep (if (pos? (count sq)) " and " "")] (apply str (concat "{" (interpose ", " (butlast sq)) [sep (last sq)] "}"))))   ; Or, using clojure.pprint's cl-format, which implements common lisp's format: (defn quibble-f [& args] (clojure.pprint/cl-format nil "{~{~a~#[~; and ~:;, ~]~}}" args))   (def test #(doseq [sq [[] ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"]]] ((comp println %) sq)))   (test quibble) (test quibble-f)
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
#EasyLang
EasyLang
items$[] = [ "iced" "jam" "plain" ] n = len items$[] k = 2 len result[] k n_results = 0 # func output . . n_results += 1 if len items$[] > 0 for r in result[] write items$[r] & " " . print "" . . func combine pos val . . if pos = k call output else for i = val to n - 1 result[pos] = i call combine pos + 1 i . . . call combine 0 0 # n = 10 k = 3 len result[] k items$[] = [ ] n_results = 0 call combine 0 0 print "" print n_results & " results with 10 donuts"
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
#EchoLisp
EchoLisp
  ;; ;; native function : combinations/rep in list.lib ;; (lib 'list)   (combinations/rep '(iced jam plain) 2) → ((iced iced) (iced jam) (iced plain) (jam jam) (jam plain) (plain plain))   ;; ;; using a combinator iterator ;; (lib 'sequences)   (take (combinator/rep '(iced jam plain) 2) 8) → ((iced iced) (iced jam) (iced plain) (jam jam) (jam plain) (plain plain))   ;; ;; or, implementing the function ;;   (define (comb/rep nums k) (cond [(null? nums) null] [(<= k 0) null] [(= k 1) (map list nums)] [else (for/fold (acc null) ((anum nums)) (append acc (for/list ((xs (comb/rep nums (1- k)))) #:continue (< (first xs) anum) (cons anum xs))))]))   (map (curry list-permute '(iced jam plain)) (comb/rep (iota 3) 2)) → ((iced iced) (iced jam) (iced plain) (jam jam) (jam plain) (plain plain))   ;; ;; extra credit ;;   (length (combinator/rep (iota 10) 3)) → 220    
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#jq
jq
def permutation(k): . as $n | reduce range($n-k+1; 1+$n) as $i (1; . * $i);   def combination(k): . as $n | if k > ($n/2) then combination($n-k) else reduce range(0; k) as $i (1; (. * ($n - $i)) / ($i + 1)) end;   # natural log of n! def log_factorial: (1+.) | tgamma | log;   def log_permutation(k): (log_factorial - ((.-k) | log_factorial));   def log_combination(k): (log_factorial - ((. - k)|log_factorial) - (k|log_factorial));   def big_permutation(k): log_permutation(k) | exp;   def big_combination(k): log_combination(k) | exp;
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Julia
Julia
  function Base.binomial{T<:FloatingPoint}(n::T, k::T) exp(lfact(n) - lfact(n - k) - lfact(k)) end   function Base.factorial{T<:FloatingPoint}(n::T, k::T) exp(lfact(n) - lfact(k)) end   ⊞{T<:Real}(n::T, k::T) = binomial(n, k) ⊠{T<:Real}(n::T, k::T) = factorial(n, n-k)