[User]
Measure a relative performance of sorting algorithms implementations.

Plot **execution time vs. input sequence length** dependencies for various implementation of sorting algorithm and different input sequence types (example figures).

Consider three type of input sequences:

:   * ones: sequence of all *1'*s.   Example: {1, 1, 1, 1, 1}
    * range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}
    * shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8}

Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm).

For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations.

Preliminary subtask:

:   * Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort
    * Query Performance
    * Write float arrays to a text file
    * Plot x, y arrays
    * Polynomial Fitting

General steps:

:   1. Define sorting routines to be considered.
    2. Define appropriate sequence generators and write timings.
    3. Plot timings.
    4. What conclusions about relative performance of the sorting routines could be made based on the plots?

[Assistant]
**Translation of**: Julia

```
# 20221114 Raku programming solution

my ($rounds,$size) = 3, 2000;
my @allones        = 1 xx $size;
my @sequential     = 1 .. $size;
my @randomized     = @sequential.roll xx $size;

sub insertion_sort ( @a is copy ) { # rosettacode.org/wiki/Sorting_algorithms/Insertion_sort#Raku
   for 1 .. @a.end -> \k {
      loop (my ($j,\value)=k-1,@a[k];$j>-1&&@a[$j]>value;$j--) {@a[$j+1]=@a[$j]}
      @a[$j+1] = value;
   }
   return @a;
}

sub merge_sort ( @a ) { # rosettacode.org/wiki/Sorting_algorithms/Merge_sort#Raku
    return @a if @a <= 1;

    my $m = @a.elems div 2;
    my @l = merge_sort @a[  0 ..^ $m ];
    my @r = merge_sort @a[ $m ..^ @a ];

    return flat @l, @r if @l[*-1] !after @r[0];
    return flat gather {
        take @l[0] before @r[0] ?? @l.shift !! @r.shift
            while @l and @r;
        take @l, @r;
    }
}

sub quick-sort(@data) { # andrewshitov.com/2019/06/23/101-quick-sort-in-perl-6/
    return @data if @data.elems <= 1;

    my ($pivot,@left, @right) = @data[0];

    for @data[1..*] -> $x { $x < $pivot ?? push @left, $x !! push @right, $x }

    return flat(quick-sort(@left), $pivot, quick-sort(@right));
}

sub comparesorts($rounds, @tosort) {
   my ( $iavg, $mavg, $qavg, $t );

   for (<i m q> xx $rounds).flat.pick(*) -> \sort_type {
      given sort_type {
         when 'i' { $t = now ; insertion_sort @tosort ; $iavg += now - $t }
         when 'm' { $t = now ; merge_sort     @tosort ; $mavg += now - $t }
	 when 'q' { $t = now ; quick-sort     @tosort ; $qavg += now - $t }
      }
   }
   return $iavg, $mavg, $qavg  »/»  $rounds
}

for <ones presorted randomized>Z(@allones,@sequential,@randomized) -> ($t,@d) {
   say "Average sort times for $size $t:";
   { say "\tinsertion sort\t$_[0]\n\tmerge sort\t$_[1]\n\tquick sort\t$_[2]" }(comparesorts $rounds,@d)
}

```

Output:

```
Average sort times for 2000 ones:
        insertion sort  0.112333083
        merge sort      0.506624066
        quick sort      5.899009606666667
Average sort times for 2000 presorted:
        insertion sort  0.03596163
        merge sort      0.474839352
        quick sort      5.896118350666666
Average sort times for 2000 randomized:
        insertion sort  5.352926729
        merge sort      0.784896982
        quick sort      0.11422247299999999
```


[User]
Some programming languages allow calculation of values at compile time.

Task

Calculate    10!    (ten factorial)   at compile time.

Print the result when the program is run.

Discuss what limitations apply to compile-time calculations in your language.

[Assistant]
(formerly Perl 6)

```
constant $tenfact = [*] 2..10;
say $tenfact;

```

Like Perl 5, we also have a BEGIN block, but it also works to introduce a blockless statement,
the value of which will be stored up to be used as an expression at run time:

```
 say BEGIN [*] 2..10;

```


[User]
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

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

---

[Assistant]
(formerly Perl 6)
Using 'while-count' example, input used is here: ast.txt

**Translation of**: Perl

```
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{ !@AST.shift ~ 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;

```

Output:

```
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
```


[User]
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).*

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:

1. the line number where the token starts
2. the column number where the token starts
3. the token name
4. the token value (only for Identifier, Integer, and String tokens)
5. 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

---

[Assistant]
(formerly Perl 6)
This is more complicated than strictly necessary for this task. It is set up to be easily adapted to do syntax analysis.

(Note: there are several bogus comments added solely to help with syntax highlighting.)

**Works with**: Rakudo version 2016.08

```
grammar tiny_C {
    rule TOP { ^ <.whitespace>? <tokens> + % <.whitespace> <.whitespace> <eoi> }

    rule whitespace { [ <comment> + % <ws> | <ws> ] }

    token comment    { '/*' ~ '*/' .*? }

    token tokens {
        [
        | <operator>   { make $/<operator>.ast   }
        | <keyword>    { make $/<keyword>.ast    }
        | <symbol>     { make $/<symbol>.ast     }
        | <identifier> { make $/<identifier>.ast }
        | <integer>    { make $/<integer>.ast    }
        | <char>       { make $/<char>.ast       }
        | <string>     { make $/<string>.ast     }
        | <error>
        ]
    }

    proto token operator    {*}
    token operator:sym<*>   { '*'               { make 'Op_multiply'    } }
    token operator:sym</>   { '/'<!before '*'>  { make 'Op_divide'      } }
    token operator:sym<%>   { '%'               { make 'Op_mod'         } }
    token operator:sym<+>   { '+'               { make 'Op_add'         } }
    token operator:sym<->   { '-'               { make 'Op_subtract'    } }
    token operator:sym('<='){ '<='              { make 'Op_lessequal'   } }
    token operator:sym('<') { '<'               { make 'Op_less'        } }
    token operator:sym('>='){ '>='              { make 'Op_greaterequal'} }
    token operator:sym('>') { '>'               { make 'Op_greater'     } }
    token operator:sym<==>  { '=='              { make 'Op_equal'       } }
    token operator:sym<!=>  { '!='              { make 'Op_notequal'    } }
    token operator:sym<!>   { '!'               { make 'Op_not'         } }
    token operator:sym<=>   { '='               { make 'Op_assign'      } }
    token operator:sym<&&>  { '&&'              { make 'Op_and'         } }
    token operator:sym<||>  { '||'              { make 'Op_or'          } }

    proto token keyword      {*}
    token keyword:sym<if>    { 'if'    { make 'Keyword_if'    } }
    token keyword:sym<else>  { 'else'  { make 'Keyword_else'  } }
    token keyword:sym<putc>  { 'putc'  { make 'Keyword_putc'  } }
    token keyword:sym<while> { 'while' { make 'Keyword_while' } }
    token keyword:sym<print> { 'print' { make 'Keyword_print' } }

    proto token symbol  {*}
    token symbol:sym<(> { '(' { make 'LeftParen'  } }
    token symbol:sym<)> { ')' { make 'RightParen' } }
    token symbol:sym<{> { '{' { make 'LeftBrace'  } }
    token symbol:sym<}> { '}' { make 'RightBrace' } }
    token symbol:sym<;> { ';' { make 'Semicolon'   } }
    token symbol:sym<,> { ',' { make 'Comma'       } }

    token identifier { <[_A..Za..z]><[_A..Za..z0..9]>* { make 'Identifier ' ~ $/ } }
    token integer    { <[0..9]>+                       { make 'Integer '    ~ $/ } }

    token char {
        '\'' [<-[']> | '\n' | '\\\\'] '\''
        { make 'Char_Literal ' ~ $/.subst("\\n", "\n").substr(1, *-1).ord }
    }

    token string {
        '"' <-["\n]>* '"' #'
        {
            make 'String ' ~ $/;
            note 'Error: Unknown escape sequence.' and exit if (~$/ ~~ m:r/ <!after <[\\]>>[\\<-[n\\]>]<!before <[\\]>> /);
        }
    }

    token eoi { $ { make 'End_of_input' } }

    token error {
        | '\'''\''                   { note 'Error: Empty character constant.' and exit }
        | '\'' <-[']> ** {2..*} '\'' { note 'Error: Multi-character constant.' and exit }
        | '/*' <-[*]>* $             { note 'Error: End-of-file in comment.'   and exit }
        | '"' <-["]>* $              { note 'Error: End-of-file in string.'    and exit }
        | '"' <-["]>*? \n            { note 'Error: End of line in string.'    and exit } #'
    }
}

sub parse_it ( $c_code ) {
    my $l;
    my @pos = gather for $c_code.lines>>.chars.kv -> $line, $v {
        take [ $line + 1, $_ ] for 1 .. ($v+1); # v+1 for newline
        $l = $line+2;
    }
    @pos.push: [ $l, 1 ]; # capture eoi

    for flat $c_code<tokens>.list, $c_code<eoi> -> $m {
        say join "\t", @pos[$m.from].fmt('%3d'), $m.ast;
    }
}

my $tokenizer = tiny_C.parse(@*ARGS[0].IO.slurp);
parse_it( $tokenizer );

```

Output  —  test case 3:

```
  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	Char_Literal 10
 21  26	Char_Literal 92
 22  26	Char_Literal 32
 23   1	End_of_input

```


[User]
Task

**Introduction**

Many programming languages allow file inclusion, so that for example, standard declarations or code-snippets can be stored in a separate source file and be included into the programs that require them at compile-time, without the need for cut-and-paste.

Probably the C pre-processor is the most well-known example.

The purpose of this task is to demonstrate how a file inclusion pre-processor could be implemented in your language, for your language. This does not mean to imply that your language needs a file inclusion pre-processor - many languages don't have such a facility.

Other languages, on the other hand do have file inclusion, e.g.: C, COBOL, PL/1.

The distinction between compiled and interpreted languages should be irrelevent - this is a specialised text processing exercise - reading a source file and producing a modified source file that aldo contains the contents of one or more other files.

Hopefully, the solutions to this task will enable the file inclusion facilities of the languages to be compared, even for languages that don't need such facilities because they have sophisticated equivalents.

**The pre-processor**

Create a simple pre-processor that implements file-inclusion for your language.

The pre-processor need not check the validity of the resultant source. The pre-processor's job is purely to insert te specified files into the source at the required points. Whether the result is syntacticly valid or not is a matter for the compiler/interpreter when it is presented with the source.

The syntax accepted for your pre-processor should be as per the standard for your language, should your language have such a facility.
E.g. for C the pre-processor must recognise and handle "#include" directives. For PL/1, %include statements would be processed and for COBOL, COPY statements, and so on.

If your language does not have a standard facility for file-inclusion, implement that used by a popular compiler/interpreter for the language.

If there is no such feature, either use the C style #include directive or choose something of your own invention, e.g., #include would be problematic for languages where # introduces a comment.

State the syntax expected and any limitations, including whether nested includes are supported and if so, how deep the nesting can be.

**Minimum requirements**

As a minimum, your pre-procdessor must be able to process a source file (read from a file or standard input, as you prefer) and generate another source file (written to a file or standard output, as you prefer). The file-inclusion directives in the source should be replaced by the contents of the specified files. Implementing nested file inclusion directives (i.e., if an included file contains another file-inclusion directive) is optional.

Pre-processors for some languages offer additional facilities, such as macro expansion and conditional compilation. Your pre-processor need not implement such things.

**Notes**

* implementors: The Task is about implementing a pre-processor for your language, not just describing it's features. Just as the task Calculating the value of e is not about using your language's in-built exp function but showing how e could be calculated, this is about showing how file inclusion could be implemented - even if the compiler/interpreter you are using already has such a facility.
* the pre-processors on this page are supplied as-is, with no warranty - use at your own peril : )

See Also

* include a file

[Assistant]
A file pre-processor is very nearly pointless for Raku. Raku is nominally an interpreted language; in actuality, it does single pass, just-in-time compilation on the fly as it loads the file. For libraries and constants (or semi constant variables) there is a robust built-in library (module) include system for code that can be pre-compiled and used on demand. `use some-library;` to import any objects exported by the module.

That's great for code references and constants, but isn't really intended for text inclusion of external files. Since the text file can not be pre-compiled, there isn't much point to having such a system. (For code at least, there are many different templating system modules for text templates; primarily, though not exclusively used for on-the-fly generation of dynamic HTML / XML documents.) One of those could certainly be bent into doing something like what this task is asking for, but are probably both over- and under-powered for the job.

1. they are mostly intended for text, not code.
2. they tend to be more geared toward inserting the content of a variable rather than the content of a file, although that could be subverted pretty easily.

So in Raku, there isn't a readily available system to do this, there isn't much point, and it's probably a bad idea...

Ah well, that never stopped us before.

A Raku script to do source filtering / preprocessing: save it and call it 'include'

```
unit sub MAIN ($file-name);
my $file = slurp $file-name;
put $file.=subst(/[^^|['{{' \s*]] '#include' \s+ (\S+) \s* '}}'?/, {run(«$*EXECUTABLE-NAME $*PROGRAM-NAME $0», :out).out.slurp(:close).trim}, :g);

```

This will find: any line starting with '#include' followed by a (absolute or relative) path to a file, or #include ./path/to/file.name enclosed in double curly brackets anywhere in the file.

It will replace the #include notation by the contents of the file referenced, will follow nested #includes arbitrarily deeply, and echo the processed file to STDOUT.

Let's test it out. Here is a test script and a bunch of include files.

Top level named... whatever, let's call it 'preprocess.raku'

```
# Top level test script file for #include Rosettacode
# 'Compiler/Simple file inclusion pre processor' task

# some code

say .³ for ^10;

#include ./include1.file

```

include1.file

```
# included #include1 file >1>
# test to ensure it only tries to execute #include of the right format

# more code
say .³³ for ^10;
# and more comments

#include    ./include2.file    # comments ok at end of include line
# <1<
```

include2.file

```
# nested #include2.file >2>
say "Test for an nested include inside a line: {{ #include ./include3.file }}";
# pointless but why not? <2<
```

include3.file

```
>3> Yep, it works! <3<

```

Invoke at a command line:

`raku include preprocess.raku`

Output:

```
# Top level test script file for #include Rosettacode
# 'Compiler/Simple file inclusion pre processor' task

# some code

say .³ for ^10;

# included #include1 file >1>
# test to ensure it only tries to execute #include of the right format

# more code
say .³³ for ^10;
# and more comments

# nested #include2.file >2>
say "Test for an nested include inside a line: >3> Yep, it works! <3<";
# pointless but why not? <2<# comments ok at end of include line
# <1<

```

You can either redirect that into a file, or just pass it back into the compiler to execute it:

`raku include preprocess.raku | raku`

Output:

```
0
1
8
27
64
125
216
343
512
729
0
1
8589934592
5559060566555523
73786976294838206464
116415321826934814453125
47751966659678405306351616
7730993719707444524137094407
633825300114114700748351602688
30903154382632612361920641803529
Test for an nested include inside a line: >3> Yep, it works! <3<
```

Note that this is not very robust, (it's 3 lines of code, what do you expect?) but it satisfies the task requirements as far as I can tell.


[User]
**Verifying Syntax**
A Syntax Analyzer that verifies a token stream,
outputs a string "true" if the token stream matches the grammar requirement,
outputs a string "false" if the token stream does not match the grammar.

**Task**
The program reads input from a file of token stream,
reads it and outputs a string "true" if the token stream matches the grammar,
outputs a string "false" and error messages if the token stream does not match the grammar,
based on the grammar below. The grammar is written in Extended Backus-Naur Form (EBNF).

**Grammar**

```
stmt         =         expr ;

expr         =         expr_level_2;
expr_level_2 =         expr_level_3 {"or" expr_level_3} ;
expr_level_3 =         expr_level_4 {"and" expr_level_4} ;
expr_level_4 = ["not"] expr_level_5 [('=' | '<') expr_level_5] ;
expr_level_5 =         expr_level_6 {('+' | '-') expr_level_6} ;
expr_level_6 =         primary      {('*' | '/') primary} ;

primary      =         Identifier
                     | Integer
                     | '(' expr ')'
                     | "true"
                     | "false"
                     ;
Integer      =         Digit {Digit};

Identifier   =         Letter {Letter | Digit | '_'};

Digit        =         "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;

Letter       =         "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j"
                     | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t"
                     | "u" | "v" | "w" | "x" | "y" | "z" | "A" | "B" | "C" | "D"
                     | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N"
                     | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X"
                     | "Y" | "Z" ;

```

[Assistant]
Format of task grammar is changed from EBNF to ABNF to cater for the Grammar::ABNF module and testing data is taken from the Perl entry.

```
# 20200511 Raku programming solution

use Grammar::ABNF;

grammar G is Grammar::ABNF { token CRLF { "\n" } };

my $g = G.generate(Q:to<RULES>
stmt         =          expr
expr         =          expr_level_2
expr_level_2 =          expr_level_3 *(      " or "       expr_level_3 )
expr_level_3 =          expr_level_4 *(      " and "      expr_level_4 )
expr_level_4 = ["not "] expr_level_5  [ [ " = " / " < " ] expr_level_5 ]
expr_level_5 =          expr_level_6 *( [ " + " / " - " ] expr_level_6 )
expr_level_6 =          primary      *( [ " * " / " / " ] primary )
Integer      =  Digit  *( Digit )
Identifier   =  Letter *( Letter / Digit / "_" )
primary      =  Identifier / Integer / "(" expr ")" / " true " / " false "
Digit        =  "0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"
Letter       =  "a" / "b" / "c" / "d" / "e" / "f" / "g" / "h" / "i" / "j"
               / "k" / "l" / "m" / "n" / "o" / "p" / "q" / "r" / "s" / "t"
               / "u" / "v" / "w" / "x" / "y" / "z" / "A" / "B" / "C" / "D"
               / "E" / "F" / "G" / "H" / "I" / "J" / "K" / "L" / "M" / "N"
               / "O" / "P" / "Q" / "R" / "S" / "T" / "U" / "V" / "W" / "X"
               / "Y" / "Z"
RULES
);

my \DATA = Q:to<DATA>;
3 + not 5
3 + (not 5)
(42 + 3
(42 + 3 syntax_error
not 3 < 4 or (true or 3 / 4 + 8 * 5 - 5 * 2 < 56) and 4 * 3 < 12 or not true
and 3 < 2
not 7 < 2
2 < 3 < 4
2 < foobar - 3 < 4
2 < foobar and 3 < 4
4 * (32 - 16) + 9 = 73
235 76 + 1
a + b = not c and false
a + b = (not c) and false
a + b = (not c and false)
ab_c / bd2 or < e_f7
g not = h
i++
j & k
l or _m
UPPER_cAsE_aNd_letter_and_12345_test
DATA

say $g.parse($_).Bool, "\t", $_ for DATA.lines

```

Output:

```
False   3 + not 5
True    3 + (not 5)
False   (42 + 3
False   (42 + 3 syntax_error
True    not 3 < 4 or (true or 3 / 4 + 8 * 5 - 5 * 2 < 56) and 4 * 3 < 12 or not true
False   and 3 < 2
True    not 7 < 2
False   2 < 3 < 4
False   2 < foobar - 3 < 4
True    2 < foobar and 3 < 4
True    4 * (32 - 16) + 9 = 73
False   235 76 + 1
False   a + b = not c and false
True    a + b = (not c) and false
True    a + b = (not c and false)
False   ab_c / bd2 or < e_f7
False   g not = h
False   i++
False   j & k
False   l or _m
True    UPPER_cAsE_aNd_letter_and_12345_test

```


[User]
Virtual Machine Interpreter

A virtual machine implements a computer in software.

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

---

[Assistant]
(formerly Perl 6)
Non-standard size of instructions (not byte-coded, 'Datasize' is 3 not 1) required adjusting the jump offsets.

NOTE: I don't think you are allowed to change the jump offsets.
They come from another program from another company from another planet from another galaxy.

WIP: discovered 'P5pack' module, this may allow for completing the task properly, using correct offsets

**Translation of**: Perl

```
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 }}();
}

```

Output:

```
count is: 1
count is: 2
count is: 3
count is: 4
count is: 5
count is: 6
count is: 7
count is: 8
count is: 9
```


[User]
Find the composite numbers **k** in base 10, that have no single digit prime factors and whose prime factors are all a substring of **k**.

Task

* Find and show here, on this page, the first ten elements of the sequence.

Stretch

* Find and show the next ten elements.

[Assistant]
```
use Prime::Factor;
use Lingua::EN::Numbers;

put (2..∞).hyper(:5000batch).map( {
    next if (1 < $_ gcd 210) || .is-prime || any .&prime-factors.map: -> $n { !.contains: $n };
    $_
} )[^20].batch(10)».&comma».fmt("%10s").join: "\n";

```

Output:

```
    15,317     59,177     83,731    119,911    183,347    192,413  1,819,231  2,111,317  2,237,411  3,129,361
 5,526,173 11,610,313 13,436,683 13,731,373 13,737,841 13,831,103 15,813,251 17,692,313 19,173,071 28,118,827
```


[User]
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

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version #24 "Seoul"

### Array

```
my @point = 3, 8;

my Int @point = 3, 8; # or constrain to integer elements
```

### Hash

```
my %point = x => 3, y => 8;

my Int %point = x => 3, y => 8; # or constrain the hash to have integer values
```

### Class instance

```
class Point { has Real ($.x, $.y) is rw; }
my Point $point .= new: x => 3, y => 8;
```

### Set

```
my $s1 = set <a b c d>; # order is not preserved
my $s2 = set <c d e f>;
say $s1 (&) $s2; # OUTPUT«set(c, e)»
say $s1 ∩ $s2; # we also do Unicode
```


[User]
Task

Find and show here when the concatenation of two primes   (**p1**,  **p2**)   shown in base ten is also prime,   where   **p1,   p2  <  100**.

[Assistant]
Inefficient, but for a limit of 100, who cares?

```
my @p = ^1e2 .grep: *.is-prime;

say display ( @p X~ @p ).grep( *.is-prime ).unique.sort( +* );

sub display ($list, :$cols = 10, :$fmt = '%6d', :$title = "{+$list} matching:\n") {
    cache $list;
    $title ~ $list.batch($cols)».fmt($fmt).join: "\n"
}

```

Output:

```
128 matching:
    23     37     53     73    113    137    173    193    197    211
   223    229    233    241    271    283    293    311    313    317
   331    337    347    353    359    367    373    379    383    389
   397    433    523    541    547    571    593    613    617    673
   677    719    733    743    761    773    797    977   1117   1123
  1129   1153   1171   1319   1361   1367   1373   1723   1741   1747
  1753   1759   1783   1789   1913   1931   1973   1979   1997   2311
  2341   2347   2371   2383   2389   2917   2953   2971   3119   3137
  3167   3719   3761   3767   3779   3797   4111   4129   4153   4159
  4337   4373   4397   4723   4729   4759   4783   4789   5323   5347
  5923   5953   6113   6131   6143   6173   6197   6719   6737   6761
  6779   7129   7159   7331   7919   7937   8311   8317   8329   8353
  8389   8923   8929   8941   8971   9719   9743   9767
```


[User]
Task

Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.

Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.9

```
my @words = <Enjoy Rosetta Code>;
@words.race(:batch(1)).map: { sleep rand; say $_ };

```

Output:

```
Code
Rosetta
Enjoy
```


[User]
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.*

[Assistant]
(formerly Perl 6)

### if/else

if, else, elsif, unless, and given work much as they do in Perl 5, with the following differences:

* All the parentheses are now optional.
* unless no longer permits elsif or else blocks.
* If the block of an if, elsif, or unless has a nonzero arity, the value of the conditional expression is used as an argument to the block:

  ```
  if won() -> $prize {
      say "You won $prize.";
  }
  ```

  If an else block has a nonzero arity, it receives the value of the condition tested by the last if or elsif.

### given/when

Switch structures are done by topicalization and by smartmatching in Raku. They are somewhat orthogonal, you can use a given block without when, and vice versa. But the typical use is:

```
given lc prompt("Done? ") {
    when 'yes' { return }
    when 'no'  { next }
    default    { say "Please answer either yes or no." }
}
```

when blocks are allowed in any block that topicalizes $\_, including a
for loop (assuming one of its loop variables is bound to $\_)
or the body of a method (if you have declared the invocant as $\_)." See more at: https://docs.raku.org/language/control#index-entry-switch\_(given)

There are also statement modifier forms of all of the above.

### Ternary operator

The ternary operator looks like this:

```
$expression ?? do_something !! do_fallback
```

### Other short-circuiting operators

and, or, &&, || and // work as in Perl 5.


[User]
Task
:   Create a program that can take a Latin verb and conjugate it, displaying in the following order:

```
1st person singular
2nd person singular
3rd person singular
1st person plural
2nd person plural
3rd person plural

```

* Each should be on its own line.
* Have at least one example from each of the 4 conjugations.
* Irregular verbs are not required.
* Translation into English is optional.

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 contain the most consonants
* Find words which contains more than 3 vowels
* Find words whose first and last three letters are equal
* Find words with alternating vowels and consonants

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
* Summarize and say sequence
* Generate lower case ASCII alphabet

See also

* Wikipedia: Latin conjugation.

[Assistant]
**Translation of**: Julia

```
for <amāre dare> -> $infinitive {
    say "\nPresent active indicative conjugation of infinitive $infinitive.";
    my $verb = ($infinitive ~~ /^ (\w+) ['a'|'ā'] 're' $/)[0];
    say $verb ?? (conjugate $verb) !! "Sorry, don't know how to conjugate $infinitive"
}

sub conjugate ($verb) { ($verb X~ <ō ās at āmus ātis ant>).join: "\n" }

```

Output:

```
Present active indicative conjugation of infinitive amāre.
amō
amās
amat
amāmus
amātis
amant

Present active indicative conjugation of infinitive dare.
dō
dās
dat
dāmus
dātis
dant
```


[User]
Suppose that a matrix

M
{\displaystyle {\displaystyle M}}
 contains complex numbers. Then the conjugate transpose of

M
{\displaystyle {\displaystyle M}}
 is a matrix

M

H
{\displaystyle {\displaystyle M^{H}}}
 containing the complex conjugates of the matrix transposition of

M
{\displaystyle {\displaystyle M}}
.

:   :   :   (

            M

            H

            )

            j
            i
            =

            M

            i
            j
            ¯
            {\displaystyle {\displaystyle (M^{H})\_{ji}={\overline {M\_{ij}}}}}

This means that row

j
{\displaystyle {\displaystyle j}}
, column

i
{\displaystyle {\displaystyle i}}
 of the conjugate transpose equals the

complex conjugate of row

i
{\displaystyle {\displaystyle i}}
, column

j
{\displaystyle {\displaystyle j}}
 of the original matrix.

In the next list,

M
{\displaystyle {\displaystyle M}}
 must also be a square matrix.

* A Hermitian matrix equals its own conjugate transpose:

  M

  H
  =
  M
  {\displaystyle {\displaystyle M^{H}=M}}
  .
* A normal matrix is commutative in multiplication with its conjugate transpose:

  M

  H
  M
  =
  M

  M

  H
  {\displaystyle {\displaystyle M^{H}M=MM^{H}}}
  .
* A unitary matrix has its inverse equal to its conjugate transpose:

  M

  H
  =

  M

  −
  1
  {\displaystyle {\displaystyle M^{H}=M^{-1}}}
  .
   This is true iff

  M

  H
  M
  =

  I

  n
  {\displaystyle {\displaystyle M^{H}M=I\_{n}}}
   and iff

  M

  M

  H
  =

  I

  n
  {\displaystyle {\displaystyle MM^{H}=I\_{n}}}
  , where

  I

  n
  {\displaystyle {\displaystyle I\_{n}}}
   is the identity matrix.

Task

Given some matrix of complex numbers, find its conjugate transpose.

Also determine if the matrix is a:

:   :   * Hermitian matrix,
        * normal matrix, or
        * unitary matrix.

See also

* MathWorld entry: conjugate transpose
* MathWorld entry: Hermitian matrix
* MathWorld entry: normal matrix
* MathWorld entry: unitary matrix

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015-12-13

```
for [ # Test Matrices
       [   1, 1+i, 2i],
       [ 1-i,   5, -3],
       [0-2i,  -3,  0]
    ],
    [
       [1, 1, 0],
       [0, 1, 1],
       [1, 0, 1]
    ],
    [
       [0.707 ,    0.707,  0],
       [0.707i, 0-0.707i,  0],
       [0     ,        0,  i]
    ]
    -> @m {
        say "\nMatrix:";
        @m.&say-it;
        my @t = @m».conj.&mat-trans;
        say "\nTranspose:";
        @t.&say-it;
        say "Is Hermitian?\t{is-Hermitian(@m, @t)}";
        say "Is Normal?\t{is-Normal(@m, @t)}";
        say "Is Unitary?\t{is-Unitary(@m, @t)}";
    }

sub is-Hermitian (@m, @t, --> Bool) {
    so @m».Complex eqv @t».Complex
 }

sub is-Normal (@m, @t, --> Bool) {
    so mat-mult(@m, @t)».Complex eqv mat-mult(@t, @m)».Complex
}

sub is-Unitary (@m, @t, --> Bool) {
    so mat-mult(@m, @t, 1e-3)».Complex eqv mat-ident(+@m)».Complex;
}

sub mat-trans (@m) { map { [ @m[*;$_] ] }, ^@m[0] }

sub mat-ident ($n) { [ map { [ flat 0 xx $_, 1, 0 xx $n - 1 - $_ ] }, ^$n ] }

sub mat-mult (@a, @b, \ε = 1e-15) {
    my @p;
    for ^@a X ^@b[0] -> ($r, $c) {
        @p[$r][$c] += @a[$r][$_] * @b[$_][$c] for ^@b;
        @p[$r][$c].=round(ε); # avoid floating point math errors
    }
    @p
}

sub say-it (@array) { $_».fmt("%9s").say for @array }

```

Output:

```
Matrix:
[        1      1+1i      0+2i]
[     1-1i         5        -3]
[     0-2i        -3         0]

Transpose:
[        1      1+1i      0+2i]
[     1-1i         5        -3]
[     0-2i        -3         0]
Is Hermitian?	True
Is Normal?	True
Is Unitary?	False

Matrix:
[        1         1         0]
[        0         1         1]
[        1         0         1]

Transpose:
[        1         0         1]
[        1         1         0]
[        0         1         1]
Is Hermitian?	False
Is Normal?	True
Is Unitary?	False

Matrix:
[    0.707     0.707         0]
[ 0+0.707i  0-0.707i         0]
[        0         0      0+1i]

Transpose:
[    0.707  0-0.707i         0]
[    0.707  0+0.707i         0]
[        0         0      0-1i]
Is Hermitian?	False
Is Normal?	True
Is Unitary?	True

```


[User]
Task

Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.

Do the same for sequences of primes where the differences are strictly descending.

In both cases, show the sequence for primes   <   1,000,000.

If there are multiple sequences of the same length, only the first need be shown.

[Assistant]
```
use Math::Primesieve;
use Lingua::EN::Numbers;

my $sieve = Math::Primesieve.new;

my $limit = 1000000;

my @primes = $sieve.primes($limit);

sub runs (&op) {
    my $diff = 1;
    my $run = 1;

    my @diff = flat 1, (1..^@primes).map: {
        my $next = @primes[$_] - @primes[$_ - 1];
        if &op($next, $diff) { ++$run } else { $run = 1 }
        $diff = $next;
        $run;
    }

    my $max = max @diff;
    my @runs = @diff.grep: * == $max, :k;

    @runs.map( {
        my @run = (0..$max).reverse.map: -> $r { @primes[$_ - $r] }
        flat roundrobin(@run».&comma, @run.rotor(2 => -1).map({[R-] $_})».fmt('(%d)'));
    } ).join: "\n"
}

say "Longest run(s) of ascending prime gaps up to {comma $limit}:\n" ~ runs(&infix:«>»);

say "\nLongest run(s) of descending prime gaps up to {comma $limit}:\n" ~ runs(&infix:«<»);

```

Output:

```
Longest run(s) of ascending prime gaps up to 1,000,000:
128,981 (2) 128,983 (4) 128,987 (6) 128,993 (8) 129,001 (10) 129,011 (12) 129,023 (14) 129,037
402,581 (2) 402,583 (4) 402,587 (6) 402,593 (8) 402,601 (12) 402,613 (18) 402,631 (60) 402,691
665,111 (2) 665,113 (4) 665,117 (6) 665,123 (8) 665,131 (10) 665,141 (12) 665,153 (24) 665,177

Longest run(s) of descending prime gaps up to 1,000,000:
322,171 (22) 322,193 (20) 322,213 (16) 322,229 (8) 322,237 (6) 322,243 (4) 322,247 (2) 322,249
752,207 (44) 752,251 (12) 752,263 (10) 752,273 (8) 752,281 (6) 752,287 (4) 752,291 (2) 752,293
```


[User]
The Consistent Overhead Byte Stuffing (COBS) algorithm is used to demarcate a byte stream into frames. Examples can be found in its Wikipedia article.

Task

To encode, instances of the byte `0x00` in the unencoded stream are substituted with the number of bytes until the next instance of `0x00` (we'll call this a milestone).
If `0x00` does not appear within the next 254 bytes after a milestone the algorithm must emit an extra milestone at the 255th byte.
Of the encoded output, the first byte is the first milestone, and the final milestone will be the number of bytes until the final byte - `0x00`.

Bonus tasks

* Decode an encoded packet
  + Report an error if the final milestone exceeds the length of the end of the packet
* Support encoding with a non-zero marker

[Assistant]
**Translation of**: Wren

```
# 20231102 Raku programming solution

sub encode($data where $data.Bool, $delim = 0x00) {
   my ($ins,$code,$addLastCode,@enc) = 0,1,True,-1;
   for $data.list -> $byte {
      if $byte != 0 { @enc.push($byte) andthen $code++ }
      $addLastCode = True;
      if $byte == 0 || $code == 255 {
         $addLastCode = False if $code == 255;
         @enc[$ins] = $code;
         $code = 1;
         $ins = @enc.elems;
         @enc.push(-1);
      }
   }
   if $addLastCode {
      @enc[$ins] = $code;
      if $delim != 0 { @enc >>^=>> $delim }
      @enc.push($delim)
   } else {
      if $delim != 0 { @enc >>^=>> $delim }
      @enc[$ins] = $delim
   }
   return @enc;
}

sub decode($data where $data.Bool, $delim = 0x00) {
   my $length = ( my @enc2 = $data.list[0..*-2] ).elems;
   if $delim != 0 { @enc2 >>^=>> $delim }
   my ($block,$code,@dec) = 0,255;
   for @enc2.kv -> $i,$byte {
      if $block != 0 {
         @dec.push($byte)
      } else {
         die "marker pointing beyond the end of the packet." if $i + $byte > $length;
         @dec.push(0) if $code != 255;
         $block = $code = $byte;
         last if $code == 0
      }
      $block--;
   }
   return @dec;
}

for ( [0x00], [0x00,0x00], [0x00,0x11,0x00], [0x11,0x22,0x00,0x33],
      [0x11,0x22,0x33,0x44], [0x11,0x00,0x00,0x00], # 0x01..0xfe, 0x00..0xfe,
#      [0x02..0xff].append(0x00), [0x03..0xff].append(0x00, 0x01),
) { # https://crccalc.com/bytestuffing.php
#   say encode( $_ )>>.&{.fmt("0x%x")};
   say decode(encode( $_ ))>>.&{.fmt("0x%x")}
}

```

You may Attempt This Online!


[User]
**Constrained genericity** or **bounded quantification** means
that a parametrized type or function (see parametric polymorphism)
can only be instantiated on types fulfilling some conditions,
even if those conditions are not used in that function.

Say a type is called "eatable" if you can call the function eat on it.
Write a generic type FoodBox which contains a collection of objects of
a type given as parameter, but can only be instantiated on eatable types.
The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type).
The specification of a type being eatable should be as generic as possible
in your language (i.e. the restrictions on the implementation of eatable types
should be as minimal as possible).
Also explain the restrictions, if any, on the implementation of eatable types,
and show at least one example of an eatable type.

[Assistant]
(formerly Perl 6)

```
subset Eatable of Any where { .^can('eat') };

class Cake { method eat() {...} }

role FoodBox[Eatable] {
    has %.foodbox;
}

class Yummy does FoodBox[Cake] { }      # composes correctly
# class Yucky does FoodBox[Int] { }     # fails to compose

my Yummy $foodbox .= new;
say $foodbox;

```

Output:

```
Yummy.new(foodbox => {})

```


[User]
Task

Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that

10
≤

x

2
+

y

2
≤
15
{\displaystyle {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.

There are several possible approaches to accomplish this. Here are two possible algorithms.

1) Generate random pairs of integers and filter out those that don't satisfy this condition:

:   10
    ≤

    x

    2
    +

    y

    2
    ≤
    15
    {\displaystyle {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}}
    .

2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015.09

```
my @range = -15..16;

my @points = gather for @range X @range -> ($x, $y) {
    take [$x,$y] if 10 <= sqrt($x*$x+$y*$y) <= 15
}
my @samples = @points.roll(100); # or .pick(100) to get distinct points

# format and print
my %matrix;
for @range X @range -> ($x, $y) { %matrix{$y}{$x} = ' ' }
%matrix{.[1]}{.[0]} = '*' for @samples;
%matrix{$_}{@range}.join(' ').say for @range;

```

Output:

```
                                  *
                    *                 *
              *     *   *         *         *
            * *         *               *
                      *           *       *   *     *
              *   *
            *     *                                   *
      *     *                                 *       *
                                              *
            *                                   * *   *
      *   *                                         *
      * *                                         *     *
      *
  *     *
                                                      * * *
  * *   * *
      *                                             *   *
    *
    *     *
  *     *
            * *                                       *
      *                                           *   *
                                          *         *
          *                                   *       *
              *         *       *         * * *     *
          *   *     *                   *     * *
                              *     *   *   *
                  *                 *
                                *     * *
```

Turning that program completely inside-out and reducing to a single statement with a single non-parameter variable, we get another version that also works.

This uses, among other things, a 0-based matrix rather than a hash, a given on the first line that allows us to print the final value of the matrix straight from its initial declaration, a for statement feeding a for statement modifier, a lambda that unpacks a single x-y argument into two variables, the functional form of pick rather than the method form, a quasi-list comprehension in the middle loop that filters each given with a when, precalculated squared limits so we don't have to take the square root, use of X- and X\*\* to subtract and exponentiate both $x and $y in parallel.

After the given do has loaded up @matrix with our circle, the map on the first line substitutes a space for any undefined matrix element, and the extra space between elements is supplied by the stringification of the list value, performed by the prefix ~ operator, the unary equivalent of concatenation in Raku.

At this point you would be justified in concluding that we are completely mad. :-)

```
(say ~.map: { $_ // ' ' } for my @matrix) given do
    -> [$x, $y] { @matrix[$x][$y] = '*' } for pick 100, do
        for ^32 X ^32 -> ($x, $y) {
            [$x,$y] when 100..225 given [+] ($x,$y X- 15) X** 2;
        }

```

Output:

```
                       *   *     *
                        * *     *
                          *       * * *   *     *
                    *   * * *         *         *
        *     *             *         *     *     *
          *     *                             *
      *                                   * * *   *
          * *                                 *     *
      * *
                                                    *   *
                                                    *
  *                                               *     *

    *                                               *
* *                                                 * * *   *
      *   *

        *                                         * *   *
          *                                         * *
      * *   *                                         *
                                                  *   *
    *   *
        * *                                     *
      * *   *                           * *           *
              *               *         *         *
              * *       *   *           *     *
              * * *                         *
                  * *   *       * *
                    *       * *
```


[User]
A number may be represented as a continued fraction (see Mathworld for more information) as follows:

:   a

    0
    +

    b

    1

    a

    1
    +

    b

    2

    a

    2
    +

    b

    3

    a

    3
    +
    ⋱
    {\displaystyle {\displaystyle a\_{0}+{\cfrac {b\_{1}}{a\_{1}+{\cfrac {b\_{2}}{a\_{2}+{\cfrac {b\_{3}}{a\_{3}+\ddots }}}}}}}}

The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:

For the square root of 2, use

a

0
=
1
{\displaystyle {\displaystyle a\_{0}=1}}
 then

a

N
=
2
{\displaystyle {\displaystyle a\_{N}=2}}
.

b

N
{\displaystyle {\displaystyle b\_{N}}}
 is always

1
{\displaystyle {\displaystyle 1}}
.

:   2
    =
    1
    +

    1

    2
    +

    1

    2
    +

    1

    2
    +
    ⋱
    {\displaystyle {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}}

For Napier's Constant, use

a

0
=
2
{\displaystyle {\displaystyle a\_{0}=2}}
, then

a

N
=
N
{\displaystyle {\displaystyle a\_{N}=N}}
.

b

1
=
1
{\displaystyle {\displaystyle b\_{1}=1}}
 then

b

N
=
N
−
1
{\displaystyle {\displaystyle b\_{N}=N-1}}
.

:   e
    =
    2
    +

    1

    1
    +

    1

    2
    +

    2

    3
    +

    3

    4
    +
    ⋱
    {\displaystyle {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}}

For Pi, use

a

0
=
3
{\displaystyle {\displaystyle a\_{0}=3}}
 then

a

N
=
6
{\displaystyle {\displaystyle a\_{N}=6}}
.

b

N
=
(
2
N
−
1

)

2
{\displaystyle {\displaystyle b\_{N}=(2N-1)^{2}}}
.

:   π
    =
    3
    +

    1

    6
    +

    9

    6
    +

    25

    6
    +
    ⋱
    {\displaystyle {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}}

See also
:   * Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015-10-31

```
sub continued-fraction(:@a, :@b, Int :$n = 100)
{
    my $x = @a[$n - 1];
    $x = @a[$_ - 1] + @b[$_] / $x for reverse 1 ..^ $n;
    $x;
}

printf "√2 ≈%.9f\n", continued-fraction(:a(1, |(2 xx *)), :b(Nil, |(1 xx *)));
printf "e  ≈%.9f\n", continued-fraction(:a(2, |(1 .. *)), :b(Nil, 1, |(1 .. *)));
printf "π  ≈%.9f\n", continued-fraction(:a(3, |(6 xx *)), :b(Nil, |((1, 3, 5 ... *) X** 2)));

```

Output:

```
√2 ≈ 1.414213562
e  ≈ 2.718281828
π  ≈ 3.141592654
```

A more original and a bit more abstract method would consist in viewing a continued fraction on rank n as a function of a variable x:

:   C
    F

    3
    (
    x
    )
    =

    a

    0
    +

    b

    1

    a

    1
    +

    b

    2

    a

    2
    +

    b

    3

    a

    3
    +
    x
    {\displaystyle {\displaystyle \mathrm {CF} \_{3}(x)=a\_{0}+{\cfrac {b\_{1}}{a\_{1}+{\cfrac {b\_{2}}{a\_{2}+{\cfrac {b\_{3}}{a\_{3}+x}}}}}}}}

Or, more consistently:

:   C
    F

    3
    (
    x
    )
    =

    a

    0
    +

    b

    0

    a

    1
    +

    b

    1

    a

    2
    +

    b

    2

    a

    3
    +

    b

    3

    x
    {\displaystyle {\displaystyle \mathrm {CF} \_{3}(x)=a\_{0}+{\cfrac {b\_{0}}{a\_{1}+{\cfrac {b\_{1}}{a\_{2}+{\cfrac {b\_{2}}{a\_{3}+{\cfrac {b\_{3}}{x}}}}}}}}}}

Viewed as such,

C
F

n
(
x
)
{\displaystyle {\displaystyle \mathrm {CF} \_{n}(x)}}
 could be written recursively:

:   C
    F

    n
    (
    x
    )
    =

    C
    F

    n
    −
    1
    (

    a

    n
    +

    b

    n
    x
    )
    {\displaystyle {\displaystyle \mathrm {CF} \_{n}(x)=\mathrm {CF} \_{n-1}(a\_{n}+{\frac {b\_{n}}{x}})}}

Or in other words:

:   C
    F

    n
    =

    C
    F

    n
    −
    1
    ∘

    f

    n
    =

    C
    F

    n
    −
    2
    ∘

    f

    n
    −
    1
    ∘

    f

    n
    =
    …
    =

    f

    0
    ∘

    f

    1
    …
    ∘

    f

    n
    {\displaystyle {\displaystyle \mathrm {CF} \_{n}=\mathrm {CF} \_{n-1}\circ f\_{n}=\mathrm {CF} \_{n-2}\circ f\_{n-1}\circ f\_{n}=\ldots =f\_{0}\circ f\_{1}\ldots \circ f\_{n}}}

where

f

n
(
x
)
=

a

n
+

b

n
x
{\displaystyle {\displaystyle f\_{n}(x)=a\_{n}+{\frac {b\_{n}}{x}}}}

Raku has a builtin composition operator. We can use it with the triangular reduction metaoperator, and evaluate each resulting function at infinity (any value would do actually, but infinite makes it consistent with this particular task).

```
sub continued-fraction(@a, @b) {
    map { .(Inf) }, [\o] map { @a[$_] + @b[$_] / * }, ^Inf
}

printf "√2 ≈ %.9f\n", continued-fraction((1, |(2 xx *)), (1 xx *))[10];
printf "e  ≈ %.9f\n", continued-fraction((2, |(1 .. *)), (1, |(1 .. *)))[10];
printf "π  ≈ %.9f\n", continued-fraction((3, |(6 xx *)), ((1, 3, 5 ... *) X** 2))[100];

```

Output:

```
√2 ≈ 1.414213552
e  ≈ 2.718281827
π  ≈ 3.141592411
```


[User]
Given a positive real number, if we truncate its continued fraction representation at a certain depth, we obtain a rational approximation to the real number. The sequence of successively better such approximations is its convergent sequence.

Problem:

* Given a positive rational number

  m
  n
  {\displaystyle {\displaystyle {\frac {m}{n}}}}
  , specified by two positive integers

  m
  ,
  n
  {\displaystyle {\displaystyle m,n}}
  , output its entire sequence of convergents.
* Given a quadratic real number

  b

  a
  +
  m
  n
  >
  0
  {\displaystyle {\displaystyle {\frac {b{\sqrt {a}}+m}{n}}>0}}
  , specified by integers

  a
  ,
  b
  ,
  m
  ,
  n
  {\displaystyle {\displaystyle a,b,m,n}}
  , where

  a
  {\displaystyle {\displaystyle a}}
   is not a perfect square, output the first

  k
  {\displaystyle {\displaystyle k}}
   convergents when given a positive number

  k
  {\displaystyle {\displaystyle k}}
  .

The output format can be whatever is necessary to represent rational numbers, but it probably should be a 2-tuple of integers.

For example, given

a
=
2
,
b
=
1
,
m
=
0
,
n
=
1
{\displaystyle {\displaystyle a=2,b=1,m=0,n=1}}
, since

2
=
1
+

1

2
+

1

2
+

1

2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
the program should output

(
1
,
1
)
,
(
3
,
2
)
,
(
7
,
5
)
,
(
17

/
12
)
,
(
41

/
29
)
,
…
{\displaystyle {\displaystyle (1,1),(3,2),(7,5),(17/12),(41/29),\dots }}
.

A simple check is to do this for the golden ratio **Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response ("Math extension cannot connect to Restbase.") from server "https://wikimedia.org/api/rest\_v1/":): {\displaystyle \frac{\sqrt{5}+1}{2}}**
, that is, **Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response ("Math extension cannot connect to Restbase.") from server "https://wikimedia.org/api/rest\_v1/":): {\displaystyle a=5, b=1, m = 1, n = 2 }**
, which should output

(
1
,
1
)
,
(
2
,
1
)
,
(
3
,
2
)
,
(
5
,
3
)
,
(
8
,
5
)
,
…
{\displaystyle {\displaystyle (1,1),(2,1),(3,2),(5,3),(8,5),\dots }}
.

Print the results for 415/93, 649/200,

2
{\displaystyle {\displaystyle {\sqrt {2}}}}
, **Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response ("Math extension cannot connect to Restbase.") from server "https://wikimedia.org/api/rest\_v1/":): {\displaystyle \sqrt{5}}**
, and the golden ratio.

References and related tasks

* Wikipedia: Continued fraction
* Continued fraction
* Continued fraction/Arithmetic
* Continued fraction/Arithmetic/Construct from rational number
* Calkin-Wilf sequence

[Assistant]
**Translation of**: Julia

```
# 20240210 Raku programming solution

sub convergents(Real $x is copy, Int $maxcount) {
   my @components = gather for ^$maxcount {
      my $fpart = $x - take $x.Int;
      $fpart == 0 ?? ( last ) !! ( $x = 1 / $fpart )
   }
   my ($numa, $denoma, $numb, $denomb) = 1, 0, @components[0], 1;
   return [ Rat.new($numb, $denomb) ].append: gather for @components[1..*] -> $comp {
      ( $numa, $denoma, $numb                , $denomb                  )
      = $numb, $denomb, $numa + $comp * $numb, $denoma + $comp * $denomb;
      take Rat.new($numb, $denomb);
   }
}

my @tests = [ "415/93", 415/93, "649/200", 649/200, "sqrt(2)", sqrt(2),
              "sqrt(5)", sqrt(5), "golden ratio", (sqrt(5) + 1) / 2     ];

say "The continued fraction convergents for the following (maximum 8 terms) are:";
for @tests -> $s, $x {
   say $s.fmt('%15s') ~ " = { convergents($x, 8).map: *.nude.join('/') } ";
}

```

Output:

```
The continued fraction convergents for the following (maximum 8 terms) are:
         415/93 = 4/1 9/2 58/13 415/93
        649/200 = 3/1 13/4 159/49 649/200
        sqrt(2) = 1/1 3/2 7/5 17/12 41/29 99/70 239/169 577/408
        sqrt(5) = 2/1 9/4 38/17 161/72 682/305 2889/1292 12238/5473 51841/23184
   golden ratio = 1/1 2/1 3/2 5/3 8/5 13/8 21/13 34/21

```

You may Attempt This Online!


[User]
To understand this task in context please see Continued fraction arithmetic

The purpose of this task is to write a function

r
2
c
f
(

i
n
t
{\displaystyle {\displaystyle {\mathit {r2cf}}(\mathrm {int} }}

N

1
,

i
n
t
{\displaystyle {\displaystyle N\_{1},\mathrm {int} }}

N

2
)
{\displaystyle {\displaystyle N\_{2})}}
, or

r
2
c
f
(

F
r
a
c
t
i
o
n
{\displaystyle {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }}

N
)
{\displaystyle {\displaystyle N)}}
, which will output a continued fraction assuming:

:   N

    1
    {\displaystyle {\displaystyle N\_{1}}}
     is the numerator
:   N

    2
    {\displaystyle {\displaystyle N\_{2}}}
     is the denominator

The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.

To achieve this it must determine: the integer part; and remainder part, of

N

1
{\displaystyle {\displaystyle N\_{1}}}
 divided by

N

2
{\displaystyle {\displaystyle N\_{2}}}
. It then sets

N

1
{\displaystyle {\displaystyle N\_{1}}}
 to

N

2
{\displaystyle {\displaystyle N\_{2}}}
 and

N

2
{\displaystyle {\displaystyle N\_{2}}}
 to the determined remainder part. It then outputs the determined integer part. It does this until

a
b
s
(

N

2
)
{\displaystyle {\displaystyle \mathrm {abs} (N\_{2})}}
 is zero.

Demonstrate the function by outputing the continued fraction for:

:   1/2
:   3
:   23/8
:   13/11
:   22/7
:   -151/77

2
{\displaystyle {\displaystyle {\sqrt {2}}}}
 should approach

[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle {\displaystyle [1;2,2,2,2,\ldots ]}}
 try ever closer rational approximations until boredom gets the better of you:

:   14142,10000
:   141421,100000
:   1414214,1000000
:   14142136,10000000

Try :

:   31,10
:   314,100
:   3142,1000
:   31428,10000
:   314285,100000
:   3142857,1000000
:   31428571,10000000
:   314285714,100000000

Observe how this rational number behaves differently to

2
{\displaystyle {\displaystyle {\sqrt {2}}}}
 and convince yourself that, in the same way as

3.7
{\displaystyle {\displaystyle 3.7}}
 may be represented as

3.70
{\displaystyle {\displaystyle 3.70}}
 when an extra decimal place is required,

[
3
;
7
]
{\displaystyle {\displaystyle [3;7]}}
 may be represented as

[
3
;
7
,
∞
]
{\displaystyle {\displaystyle [3;7,\infty ]}}
 when an extra term is required.

[Assistant]
(formerly Perl 6)
Straightforward implementation:

```
sub r2cf(Rat $x is copy) {
    gather loop {
	$x -= take $x.floor;
	last unless $x > 0;
	$x = 1 / $x;
    }
}

say r2cf(.Rat) for <1/2 3 23/8 13/11 22/7 1.41 1.4142136>;

```

Output:

```
(0 2)
(3)
(2 1 7)
(1 5 2)
(3 7)
(1 2 2 3 1 1 2)
(1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2)
```

As a silly one-liner:

```
sub r2cf(Rat $x is copy) { gather $x [R/]= 1 while ($x -= take $x.floor) > 0 }

```


[User]
This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:

:   [

    a

    1

    a

    b

    1

    b
    ]
    {\displaystyle {\displaystyle {\begin{bmatrix}a\_{1}&a\\b\_{1}&b\end{bmatrix}}}}

I may perform perform the following operations:

:   Input the next term of N1
:   Output a term of the continued fraction resulting from the operation.

I output a term if the integer parts of

a
b
{\displaystyle {\displaystyle {\frac {a}{b}}}}
 and

a

1

b

1
{\displaystyle {\displaystyle {\frac {a\_{1}}{b\_{1}}}}}
 are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject

∞
{\displaystyle {\displaystyle \infty }}
.

When I input a term t my internal state:

[

a

1

a

b

1

b
]
{\displaystyle {\displaystyle {\begin{bmatrix}a\_{1}&a\\b\_{1}&b\end{bmatrix}}}}
 is transposed thus

[

a
+

a

1
∗
t

a

1

b
+

b

1
∗
t

b

1
]
{\displaystyle {\displaystyle {\begin{bmatrix}a+a\_{1}\*t&a\_{1}\\b+b\_{1}\*t&b\_{1}\end{bmatrix}}}}

When I output a term t my internal state:

[

a

1

a

b

1

b
]
{\displaystyle {\displaystyle {\begin{bmatrix}a\_{1}&a\\b\_{1}&b\end{bmatrix}}}}
 is transposed thus

[

b

1

b

a

1
−

b

1
∗
t

a
−
b
∗
t
]
{\displaystyle {\displaystyle {\begin{bmatrix}b\_{1}&b\\a\_{1}-b\_{1}\*t&a-b\*t\end{bmatrix}}}}

When I need a term t but there are no more my internal state:

[

a

1

a

b

1

b
]
{\displaystyle {\displaystyle {\begin{bmatrix}a\_{1}&a\\b\_{1}&b\end{bmatrix}}}}
 is transposed thus

[

a

1

a

1

b

1

b

1
]
{\displaystyle {\displaystyle {\begin{bmatrix}a\_{1}&a\_{1}\\b\_{1}&b\_{1}\end{bmatrix}}}}

I am done when b1 and b are zero.

Demonstrate your solution by calculating:

:   [1;5,2] + 1/2
:   [3;7] + 1/2
:   [3;7] divided by 4

Using a generator for

2
{\displaystyle {\displaystyle {\sqrt {2}}}}
 (e.g., from Continued fraction) calculate

1

2
{\displaystyle {\displaystyle {\frac {1}{\sqrt {2}}}}}
. You are now at the starting line for using Continued Fractions to implement Arithmetic-geometric mean without ulps and epsilons.

The first step in implementing Arithmetic-geometric mean is to calculate

1
+

1

2
2
{\displaystyle {\displaystyle {\frac {1+{\frac {1}{\sqrt {2}}}}{2}}}}
 do this now to cross the starting line and begin the race.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.08.1

All the important stuff takes place in the NG object. Everything else is helper subs for testing and display. The NG object is capable of working with infinitely long continued fractions, but displaying them can be problematic. You can pass in a limit to the apply method to get a fixed maximum number of terms though. See the last example: 100 terms from the infinite cf (1+√2)/2 and its Rational representation.

```
class NG {
    has ( $!a1, $!a, $!b1, $!b );
    submethod BUILD ( :$!a1, :$!a, :$!b1, :$!b ) { }

    # Public methods
    method new( $a1, $a, $b1, $b ) { self.bless( :$a1, :$a, :$b1, :$b ) }
    method apply(@cf, :$limit = Inf) {
        (gather {
            map { take self!extract unless self!needterm; self!inject($_) }, @cf;
            take self!drain until self!done;
        })[ ^ $limit ]
    }

    # Private methods
    method !inject ($n) {
        sub xform($n, $x, $y) { $x, $n * $x + $y }
        ( $!a, $!a1 ) = xform( $n, $!a1, $!a );
        ( $!b, $!b1 ) = xform( $n, $!b1, $!b );
    }
    method !extract {
        sub xform($n, $x, $y) { $y, $x - $y * $n }
        my $n = $!a div $!b;
        ($!a,  $!b ) = xform( $n, $!a,  $!b  );
        ($!a1, $!b1) = xform( $n, $!a1, $!b1 );
        $n
    }
    method !drain { $!a = $!a1, $!b = $!b1 if self!needterm; self!extract }
    method !needterm { so [||] !$!b, !$!b1, $!a/$!b != $!a1/$!b1 }
    method !done { not [||] $!b, $!b1 }
}

sub r2cf(Rat $x is copy) { # Rational to continued fraction
    gather loop {
	$x -= take $x.floor;
	last if !$x;
	$x = 1 / $x;
    }
}

sub cf2r(@a) { # continued fraction to Rational
    my $x = @a[* - 1]; # Use FatRats for arbitrary precision
    $x = ( @a[$_- 1] + 1 / $x ).FatRat for reverse 1 ..^ @a;
    $x
}

sub ppcf(@cf) { # format continued fraction for pretty printing
    "[{ @cf.join(',').subst(',',';') }]"
}

sub pprat($a) { # format Rational for pretty printing
   # Use FatRats for arbitrary precision
   $a.FatRat.denominator == 1 ?? $a !! $a.FatRat.nude.join('/')
}

sub test_NG ($rat, @ng, $op) {
    my @cf = $rat.Rat(1e-18).&r2cf;
    my @op = NG.new( |@ng ).apply( @cf );
    say $rat.raku, ' as a cf: ', @cf.&ppcf, " $op = ",
        @op.&ppcf, "\tor ", @op.&cf2r.&pprat, "\n";
}

# Testing
test_NG(|$_) for (
    [ 13/11, [<2 1 0 2>], '+ 1/2 '    ],
    [ 22/7,  [<2 1 0 2>], '+ 1/2    ' ],
    [ 22/7,  [<1 0 0 4>], '/ 4      ' ],
    [ 22/7,  [<7 0 0 22>], '* 7/22   ' ],
    [ 2**.5, [<1 1 0 2>], "\n(1+√2)/2 (approximately)" ]
);

say '100 terms of (1+√2)/2 as a continued fraction and as a rational value:';

my @continued-fraction = NG.new( 1,1,0,2 ).apply( (lazy flat 1, 2 xx * ), limit => 100 );
say @continued-fraction.&ppcf.comb(/ . ** 1..80/).join("\n");
say @continued-fraction.&cf2r.&pprat;

```

Output:

```
<13/11> as a cf: [1;5,2] + 1/2  = [1;1,2,7]	or 37/22

<22/7> as a cf: [3;7] + 1/2     = [3;1,1,1,4]	or 51/14

<22/7> as a cf: [3;7] / 4       = [0;1,3,1,2]	or 11/14

<22/7> as a cf: [3;7] * 7/22    = [1]	or 1

1.4142135623731e0 as a cf: [1;2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
(1+√2)/2 (approximately) = [1;4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4]	or 225058681/186444716

100 terms of (1+√2)/2 and its rational value
[1;4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4
,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4
,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4]
161733217200188571081311986634082331709/133984184101103275326877813426364627544

```