{$mode delphi}
PROGRAM notes;
// Notes: a time-stamped command line notebook
// usage: >notes "note"< or >notes< to display contents
USES Classes, SysUtils;

VAR
	Note  : TStringList;
	Fname : STRING = 'Notes.txt';
	Dtime : STRING;
	Ntext : STRING;
	c     : Cardinal;

BEGIN
	DTime := FormatDateTime('YYYY-MM-DD-hhnn',Now);
	Note  := TStringList.Create;
	WITH Note DO BEGIN
		TRY
			LoadFromFile(Fname);
		EXCEPT
			Add(DTime);
			NText := 'Notes.txt created.';
		END;
		// command line args present:
		// add note with date & time
		IF ParamStr(1) <> '' THEN BEGIN
			NText := ParamStr(1);
			Add(DTime);
			Add(NText);
			SaveToFile(Fname);
		// command line args absent:
		// display contents of notebook
		END ELSE
			FOR c := 0 TO Count-1 DO
				Writeln(Note[c]);
		Free;
	END;
END.


findTaxi[n_] := Sort[Keys[Select[Counts[Flatten[Table[x^3 + y^3, {x, 1, n}, {y, x, n}]]], GreaterThan[1]]]];
Take[findTaxiNumbers[100], 25]
found=findTaxiNumbers[1200][[2000 ;; 2005]]
Map[Reduce[x^3 + y^3 == # && x >= y && x > 0 && y > 0, {x, y}, Integers] &, found]


import heapqueue, strformat

type

  CubeSum = tuple[x, y, value: int]

# Comparison function needed for the heap queues.
proc `<`(c1, c2: CubeSum): bool = c1.value < c2.value

template cube(n: int): int = n * n * n

iterator cubesum(): CubeSum =
  var queue: HeapQueue[CubeSum]
  var n = 1
  while true:
    while queue.len == 0 or queue[0].value > cube(n):
      queue.push (n, 1, cube(n) + 1)
      inc n
    var s = queue.pop()
    yield s
    inc s.y
    if s.y < s.x: queue.push (s.x, s.y, cube(s.x) + cube(s.y))

iterator taxis(): seq[CubeSum] =
  var result: seq[CubeSum] = @[(0, 0, 0)]
  for s in cubesum():
    if s.value == result[^1].value:
      result.add s
    else:
      if result.len > 1: yield result
      result.setLen(0)
      result.add s      # These two statements are faster than the single result = @[s].

var n = 0
for t in taxis():
  inc n
  if n > 2006: break
  if n <= 25 or n >= 2000:
    stdout.write &"{n:4}: {t[0].value:10}"
    for s in t:
      stdout.write &" = {s.x:4}^3 + {s.y:4}^3"
    echo()


my $file = 'notes.txt';
if ( @ARGV ) {
  open NOTES, '>>', $file or die "Can't append to file $file: $!";
  print NOTES scalar localtime, "\n\t@ARGV\n";
} else {
  open NOTES, '<', $file or die "Can't read file $file: $!";
  print <NOTES>;
}
close NOTES;


without js -- (file i/o)
constant cmd = command_line(),
         filename = "notes.txt"
if length(cmd)<3 then
    object text = get_text(filename)
    printf(1,"%s\n",iff(string(text)?text:"<empty>"))
else
    integer fn = open(filename,"a")
    printf(fn,"%d-%02d-%02d %d:%02d:%02d\n",date())
    printf(fn,"\t%s\n",join(cmd[3..$]))
    close(fn)
end if


#!/usr/bin/php
<?php
if ($argc > 1)
    file_put_contents(
        'notes.txt',
        date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
        FILE_APPEND
    );
else
    @readfile('notes.txt');


taxicab(n)=my(t); for(k=sqrtnint((n-1)\2,3)+1, sqrtnint(n,3), if(ispower(n-k^3, 3), if(t, return(1), t=1))); 0;
cubes(n)=my(t); for(k=sqrtnint((n-1)\2,3)+1, sqrtnint(n,3), if(ispower(n-k^3, 3, &t), print(n" =  \t"k"^3\t+ "t"^3")))
select(taxicab, [1..402597])
apply(cubes, %);


#!/usr/bin/picolisp /usr/lib/picolisp/lib.l

(load "@lib/misc.l")
(if (argv)
   (out "+notes.txt" (prinl (stamp) "^J^I" (glue " " @)))
   (and (info "notes.txt") (in "notes.txt" (echo))) )
(bye)


NOTES: procedure (text) options (main); /* 8 April 2014 */
   declare text character (100) varying;
   declare note_file file;

   on undefinedfile(note_file) go to file_does_not_exist;
   open file (note_file) title ('/NOTES.TXT,recsize(100),type(text)');
   revert error;

   if text = '' then
      do;
         on endfile (note_file) stop;

         do forever;
            get file (note_file) edit (text) (L);
            put skip list (text);
         end;
      end;
   close file (note_file);
   open file (note_file) output title ('/NOTES.TXT,recsize(100),type(text),append(y)');

   put file (note_file) skip list (DATETIME('DDMmmYYYY'), TIME());
   put file (note_file) skip list (text);
   put file (note_file) skip;

   put skip list ('Appended ' || text || ' to file');

   return;

file_does_not_exist:
   revert undefinedfile (note_file);
   close file (note_file);
   open file (note_file) output title ('/NOTES.TXT,recsize(100),type(text)');
   put file (note_file) skip list (DATETIME('DDMmmYYYY'), TIME());
   put file (note_file) skip list (text);
   put file (note_file) skip;
   put skip list ('The file, NOTES.TXT, has been created');
end NOTES;


$notes = "notes.txt"
if (($args).length -eq 0) {
    if(Test-Path $notes) {
        Get-Content $notes
    }
} else {
    Get-Date | Add-Content $notes
    "`t" + $args -join " " | Add-Content $notes
}


#FileName="notes.txt"
Define argc=CountProgramParameters()
If OpenConsole()
  If argc=0
    If ReadFile(0,#FileName)
      While Eof(0)=0
        PrintN(ReadString(0))                    ; No new notes, so present the old
      Wend
      CloseFile(0)
    EndIf
  Else ; e.g. we have some arguments
    Define d$=FormatDate("%yyyy-%mm-%dd %hh:%ii:%ss",date())
    If OpenFile(0,#FileName)
      Define args$=""
      While argc
        args$+" "+ProgramParameter()             ; Read all arguments
        argc-1
      Wend
      FileSeek(0,Lof(0))                         ; Go to the end of this file
      WriteStringN(0,d$+#CRLF$+#TAB$+args$)      ; Append date & note
      CloseFile(0)
    EndIf
  EndIf
EndIf


program taxiCabNo;
uses
  sysutils;
type
  tPot3    = Uint32;
  tPot3Sol = record
               p3Sum : tPot3;
               i1,j1,
               i2,j2 : Word;
             end;
 tpPot3    = ^tPot3;
 tpPot3Sol = ^tPot3Sol;

var
//1290^3 = 2'146'689'000 < 2^31-1
//1190 is the magic number of the task ;-)
  pot3 : array[0..1190{1290}] of tPot3;//
  AllSol : array[0..3000] of tpot3Sol;
  AllSolHigh : NativeInt;

procedure SolOut(const s:tpot3Sol;no: NativeInt);
begin
  with s do
    writeln(no:5,p3Sum:12,' = ',j1:5,'^3 +',i1:5,'^3 =',j2:5,'^3 +',i2:5,'^3');
end;

procedure InsertAllSol;

var
  tmp: tpot3Sol;
  p :tpPot3Sol;
  p3Sum: tPot3;
  i: NativeInt;
Begin

  i := AllSolHigh;
  IF i > 0 then
  Begin
    p := @AllSol[i];
    tmp := p^;
    p3Sum := p^.p3Sum;
    //search the right place for insertion
    repeat
      dec(i);
      dec(p);
      IF (p^.p3Sum <= p3Sum) then
        BREAK;
    until  (i<=0);
    IF p^.p3Sum = p3Sum then
      EXIT;
    //free the right place by moving one place up
    inc(i);
    inc(p);
    IF i<AllSolHigh then
    Begin
      move(p^,AllSol[i+1],SizeOf(AllSol[0])*(AllSolHigh-i));
      p^ := tmp;
    end;
  end;
  inc(AllSolHigh);
end;

function searchSameSum(var sol:tpot3Sol):boolean;
//try to find a new combination for the same sum
//within the limits given by lo and hi
var
  Sum,
  SumLo: tPot3;
  hi,lo: NativeInt;
Begin
  with Sol do
  Begin
    Sum := p3Sum;
    lo:= i1;
    hi:= j1;
  end;

  repeat
    //Move hi down
    dec(hi);
    SumLo := Sum-Pot3[hi];
    //Move lo up an check until new combination found or implicite lo> hi
    repeat
      inc(lo)
    until (SumLo<=Pot3[lo]);
    //found?
    IF SumLo = Pot3[lo] then
      BREAK;
  until lo>=hi;

  IF lo<hi then
  Begin
    sol.i2:= lo;
    sol.j2:= hi;
    searchSameSum := true;
  end
  else
    searchSameSum := false;
end;

procedure Search;
var
  i,j: LongInt;
Begin
  AllSolHigh := 0;
  For j := 2 to High(pot3)-1 do
  Begin
    For i := 1 to j-1 do
    Begin
      with AllSol[AllSolHigh] do
      Begin
        p3Sum:= pot3[i]+pot3[j];
        i1:= i;
        j1:= j;
      end;
      IF searchSameSum(AllSol[AllSolHigh]) then
      BEGIN
        InsertAllSol;
        IF AllSolHigh>High(AllSol) then EXIT;
      end;
    end;
  end;
end;

var
  i: LongInt;
Begin
  For i := Low(pot3) to High(pot3) do
    pot3[i] := i*i*i;
  AllSolHigh := 0;
  Search;
  For i :=    0 to   24 do SolOut(AllSol[i],i+1);
  For i := 1999 to 2005 do SolOut(AllSol[i],i+1);
  writeln('count of solutions         ',AllSolHigh);
end.


import sys, datetime, shutil

if len(sys.argv) == 1:
    try:
        with open('notes.txt', 'r') as f:
            shutil.copyfileobj(f, sys.stdout)
    except IOError:
        pass
else:
    with open('notes.txt', 'a') as f:
        f.write(datetime.datetime.now().isoformat() + '\n')
        f.write("\t%s\n" % ' '.join(sys.argv[1:]))


#!/usr/bin/env Rscript --default-packages=methods

args <- commandArgs(trailingOnly=TRUE)

if (length(args) == 0) {
  conn <- file("notes.txt", 'r')
  cat(readLines(conn), sep="\n")
} else {
  conn <- file("notes.txt", 'a')
  cat(file=conn, date(), "\n\t", paste(args, collapse=" "), "\n", sep="")
}
close(conn)


#!/usr/bin/env racket
#lang racket
(define file "NOTES.TXT")
(require racket/date)
(command-line #:args notes
  (if (null? notes)
    (if (file-exists? file)
      (call-with-input-file* file
        (λ(i) (copy-port i (current-output-port))))
      (raise-user-error 'notes "missing ~a file" file))
    (call-with-output-file* file #:exists 'append
      (λ(o) (fprintf o "~a\n\t~a\n"
                     (date->string (current-date) #t)
                     (string-join notes))))))


my $file = 'notes.txt';

multi MAIN() {
    print slurp($file);
}

multi MAIN(*@note) {
    my $fh = open($file, :a);
    $fh.say: DateTime.now, "\n\t", @note;
    $fh.close;
}


my($beg, $end) = (@ARGV==0) ? (1,25) : (@ARGV==1) ? (1,shift) : (shift,shift);

my $lim = 1e14;  # Ought to be dynamic as should segment size
my @basis = map { $_*$_*$_ } (1 .. int($lim ** (1.0/3.0) + 1));
my $paira = 2;  # We're looking for Ta(2) and larger

my ($segsize, $low, $high, $i) = (500_000_000, 0, 0, 0);

while ($i < $end) {
  $low = $high+1;
  die "lim too low" if $low > $lim;
  $high = $low + $segsize - 1;
  $high = $lim if $high > $lim;
  foreach my $p (_find_pairs_segment(\@basis, $paira, $low, $high,
                 sub { sprintf("%4d^3 + %4d^3", $_[0], $_[1]) })    ) {
    $i++;
    next if $i < $beg;
    last if $i > $end;
    my $n = shift @$p;
    printf "%4d: %10d  = %s\n", $i, $n, join("  = ", @$p);
  }
}

sub _find_pairs_segment {
  my($p, $len, $start, $end, $formatsub) = @_;
  my $plen = $#$p;

  my %allpairs;
  foreach my $i (0 .. $plen) {
    my $pi = $p->[$i];
    next if ($pi+$p->[$plen]) < $start;
    last if (2*$pi) > $end;
    foreach my $j ($i .. $plen) {
      my $sum = $pi + $p->[$j];
      next if $sum < $start;
      last if $sum > $end;
      push @{ $allpairs{$sum} }, $i, $j;
    }
    # If we wanted to save more memory, we could filter and delete every entry
    # where $n < 2 * $p->[$i+1].  This can cut memory use in half, but is slow.
  }

  my @retlist;
  foreach my $list (grep { scalar @$_ >= $len*2 } values %allpairs) {
    my $n = $p->[$list->[0]] + $p->[$list->[1]];
    my @pairlist;
    while (@$list) {
      push @pairlist, $formatsub->(1 + shift @$list, 1 + shift @$list);
    }
    push @retlist, [$n, @pairlist];
  }
  @retlist = sort { $a->[0] <=> $b->[0] } @retlist;
  return @retlist;
}


rebol [
   Title: "Notes"
   URL: http://rosettacode.org/wiki/Take_notes_on_the_command_line
]

notes: %notes.txt

either any [none? args: system/script/args  empty? args] [
   if exists? notes [print read notes]
] [
   write/binary/append notes rejoin [now lf tab args lf]
]


/*REXX program  implements the  "NOTES"  command  (append text to a file from the C.L.).*/
timestamp=right(date(),11,0)  time()  date('W')  /*create a (current) date & time stamp.*/
nFID = 'NOTES.TXT'                               /*the  fileID  of the  "notes"  file.  */

if 'f2'x==2  then tab="05"x                      /*this is an EBCDIC system.            */
             else tab="09"x                      /*  "   "  "  ASCII    "               */

if arg()==0  then do  while lines(nFID)          /*No arguments?  Then display the file.*/
                  say linein(Nfid)               /*display  a  line of file ──► screen. */
                  end   /*while*/
             else do
                  call lineout nFID,timestamp    /*append the timestamp to "notes" file.*/
                  call lineout nFID,tab||arg(1)  /*   "    "     text    "    "      "  */
                  end
                                                 /*stick a fork in it,  we're all done. */


notes = 'NOTES.TXT'
if ARGV.empty?
  File.copy_stream(notes, $stdout) rescue nil
else
  File.open(notes, 'a') {|file| file.puts "%s\n\t%s" % [Time.now, ARGV.join(' ')]}
end


-- demo\rosetta\Taxicab_numbers.exw
with javascript_semantics
function cube_sums()
    // create cubes and sorted list of cube sums
    sequence cubes = {}, sums = {}
    for i=1 to 1189 do
        atom cube = i * i * i
        sums &= sq_add(cubes,cube)
        cubes &= cube
    end for
    sums = sort(sums) -- (706,266 in total)
    return {cubes,sums}
end function

sequence {cubes, sums} = cube_sums()

atom nm1 = sums[1],
       n = sums[2]
integer idx = 1
printf(1,"First 25 Taxicab Numbers, 2000..2006th, and all interim triples:\n")
for i=3 to length(sums) do
    atom np1 = sums[i]
    if n=np1 and n!=nm1 then
        if idx<=25
        or (idx>=2000 and idx<=2006)
        or n=sums[i+1] then
            sequence s = {}
            for j=1 to length(cubes) do
                atom x = cubes[j],
                     y = n-x
                if y<x then exit end if
                integer ydx = binary_search(y,cubes)
                if ydx>0 then
                    s = append(s,sprintf("(%3d^3=%9d) + (%4d^3=%10d)",{j,x,ydx,y}))
                end if
            end for
            printf(1,"%4d %10d = %s\n",{idx,n,join(s," or ")})
        end if
        idx += 1
    end if
    nm1 = n
    n = np1
end for


extern crate chrono;

use std::fs::OpenOptions;
use std::io::{self, BufReader, BufWriter};
use std::io::prelude::*;
use std::env;

const FILENAME: &str = "NOTES.TXT";

fn show_notes() -> Result<(), io::Error> {
    let file = OpenOptions::new()
        .read(true)
        .create(true) // create the file if not found
        .write(true) // necessary to create the file
        .open(FILENAME)?;
    let mut buf_reader = BufReader::new(file);
    let mut contents = String::new();
    buf_reader.read_to_string(&mut contents)?;
    println!("{}", contents);
    Ok(())
}

fn add_to_notes(note: &str) -> Result<(), io::Error> {
    let file = OpenOptions::new()
        .append(true) // disables overwriting, writes to the end of the file
        .create(true)
        .open(FILENAME)?;
    let mut buf_writer = BufWriter::new(file);

    let date_and_time = chrono::Local::now();
    writeln!(buf_writer, "{}", date_and_time)?;

    writeln!(buf_writer, "\t{}", note)
}

fn main() {
    let note = env::args().skip(1).collect::<Vec<_>>();

    if note.is_empty() {
        show_notes().expect("failed to print NOTES.TXT");
    } else {
        add_to_notes(&note.join(" ")).expect("failed to write to NOTES.TXT");
    }
}


import java.io.{ FileNotFoundException, FileOutputStream, PrintStream }
import java.time.LocalDateTime

object TakeNotes extends App {
  val notesFileName = "notes.txt"
  if (args.length > 0) {
    val ps = new PrintStream(new FileOutputStream(notesFileName, true))
    ps.println(LocalDateTime.now() + args.mkString("\n\t", " ", "."))
    ps.close()
  } else try {
    io.Source.fromFile(notesFileName).getLines().foreach(println)
  } catch {
    case e: FileNotFoundException => println(e.getLocalizedMessage())
    case e: Throwable => {
      println("Some other exception type:")
      e.printStackTrace()
    }
  }
}


#lang racket
(require racket/date)
(define *notes* "NOTES.TXT")

(let ([a (vector->list (current-command-line-arguments))])
  (cond
    [(empty? a)
     (with-handlers ([exn:fail? void])
       (call-with-input-file *notes*
         (lambda (fi)
           (copy-port fi (current-output-port)))))
     ]
    [else
     (call-with-output-file *notes*
       (lambda (fo)
         (let ([ln (apply string-append (add-between a " "))]
               [dt (date->string (current-date))])
           (fprintf fo "~a~n\t~a~n" dt ln)))
       #:mode 'text #:exists 'append)
     ]))


(load "@lib/simul.l")

(off 'B)
(for L (subsets 2 (range 1 1200))
   (let K (sum '((N) (** N 3)) L)
      (ifn (lup B K)
         (idx 'B (list K 1 (list L)) T)
         (inc (cdr @))
         (push (cddr @) L) ) ) )
(setq R
   (filter
      '((L) (>= (cadr L) 2))
      (idx 'B)) )
(for L (head 25 R)
   (println (car L) (caddr L)) )
(for L (head 7 (nth R 2000))
   (println (car L) (caddr L)) )


#MAX=1189

Macro q3(a,b)
  a*a*a+b*b*b
EndMacro

Structure Cap
  x.i
  y.i
  s.i
EndStructure

NewList Taxi.Cap()

For i=1 To #MAX
  For j=i To #MAX
    AddElement(Taxi()) : Taxi()\s=q3(i,j) : Taxi()\x=i : Taxi()\y=j
  Next j
Next i

SortStructuredList(Taxi(),#PB_Sort_Ascending,OffsetOf(Cap\s),TypeOf(Cap\s))

If OpenConsole()
  ForEach Taxi()
    If sum=Taxi()\s
      r$+"="+RSet(Str(Taxi()\x),4)+"³ +"+RSet(Str(Taxi()\y),4)+"³ " : Continue
    EndIf
    If CountString(r$,"=")>=2 : c+1 : EndIf
    If CountString(r$,"=")=2
      Select c
        Case 1 To 25, 2000 To 2006 : PrintN(RSet(Str(c),5)+": "+RSet(Str(sum),10)+r$)
        Case Bool(c>2006) : Break
      EndSelect
    EndIf
    r$=""
    sum=Taxi()\s : r$="="+RSet(Str(Taxi()\x),4)+"³ +"+RSet(Str(Taxi()\y),4)+"³ "
  Next
  PrintN("FIN.") : Input()
EndIf


$ include "seed7_05.s7i";
$ include "getf.s7i";
$ include "time.s7i";

const string: noteFileName is "NOTES.TXT";

const proc: main is func
  local
    var file: note is STD_NULL;
  begin
    if length(argv(PROGRAM)) = 0 then
      # write NOTES.TXT
      write(getf(noteFileName));
    else
      # Write date & time to NOTES.TXT, and then arguments
      note := open(noteFileName, "a");
      if note <> STD_NULL then
        writeln(note, truncToSecond(time(NOW)));
        writeln(note, "\t" <& join(argv(PROGRAM), " "));
        close(note);
      end if;
    end if;
  end func;


var file = %f'notes.txt'

if (ARGV.len > 0) {
    var fh = file.open_a
    fh.say(Time.local.ctime + "\n\t" + ARGV.join(" "))
    fh.close
} else {
    var fh = file.open_r
    fh && fh.each { .say }
}


#! /usr/local/bin/snobol4 -b
	a = 2 ;* skip '-b' parameter
	notefile = "notes.txt"
while 	args = args host(2,a = a + 1) " "		:s(while)
	ident(args)	:f(append)
noparms	input(.notes,io_findunit(),,notefile)		:s(display)f(end)
display	output = notes					:s(display)
	endfile(notes)					:(end)
append	output(.notes,io_findunit(),"A",notefile)	:f(end)
	notes = date()
	notes = char(9) args
end


import Foundation

let args = Process.arguments
let manager = NSFileManager()
let currentPath = manager.currentDirectoryPath
var err:NSError?

// Create file if it doesn't exist
if !manager.fileExistsAtPath(currentPath + "/notes.txt") {
    println("notes.txt doesn't exist")
    manager.createFileAtPath(currentPath + "/notes.txt", contents: nil, attributes: nil)
}

// handler is what is used to write to the file
let handler = NSFileHandle(forUpdatingAtPath: currentPath + "/notes.txt")

// Print the file if there are no args
if args.count == 1 {
    let str = NSString(contentsOfFile: currentPath + "/notes.txt", encoding: NSUTF8StringEncoding, error: &err)
    println(str!)
    exit(0)
}

let time = NSDate()
let format = NSDateFormatter()
let timeData = (format.stringFromDate(time) + "\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
format.dateFormat = "yyyy.MM.dd 'at' HH:mm:ss zzz"

// We're writing to the end of the file
handler?.seekToEndOfFile()
handler?.writeData(timeData!)

var str = "\t"
for i in 1..<args.count {
    str += args[i] + " "
}

str += "\n"

let strData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
handler?.writeData(strData!)


from collections import defaultdict
from itertools import product
from pprint import pprint as pp

cube2n = {x**3:x for x in range(1, 1201)}
sum2cubes = defaultdict(set)
for c1, c2 in product(cube2n, cube2n):
	if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))

taxied = sorted((k, v) for k,v in sum2cubes.items() if len(v) >= 2)

#pp(len(taxied))  # 2068
for t in enumerate(taxied[:25], 1):
    pp(t)
print('...')
for t in enumerate(taxied[2000-1:2000+6], 2000):
    pp(t)


# Make it easier to change the name of the notes file
set notefile notes.txt

if {$argc} {
    # Write a message to the file
    set msg [clock format [clock seconds]]\n\t[join $argv " "]
    set f [open $notefile a]
    puts $f $msg
    close $f
} else {
    # Print the contents of the file
    catch {
	set f [open $notefile]
	fcopy $f stdout
	close $f
    }
}


If Cmd (0) > 1 Then                    ' if there are commandline arguments
  If Set (a, Open ("notes.txt", "a")) < 0 Then
    Print "Cannot write \qnotes.txt\q" ' open the file in "append" mode
    End                                ' on error, issue message and exit
  EndIf
                                       ' write the date and time
  Write a, Show (FUNC(_DateStr (Time ())));" ";Show (FUNC(_TimeStr (Time ())))

  Write a, "\t";                       ' prepend with a tab
  For i = 2 To Cmd (0) - 1             ' now write all commandline arguments
    Write a, Show (Cmd (i)); " ";      ' with the exception of the last one
  Next

  Write a, Show (Cmd (Cmd (0)))        ' write the last argument
Else                                   ' if no commandline arguments are given
  If Set (a, Open ("notes.txt", "r")) < 0 Then
    Print "Cannot read \qnotes.txt\q"  ' open the file in "read" mode
    End                                ' on error, issue message and exit
  EndIf

  Do While Read (a)                    ' read until EOF
    Print Show (Tok (0))               ' show the entire line
  Loop                                 ' and repeat..
EndIf

Close a                                ' finally, close the file
End

_DateStr                               ' convert epoch to date string
  Param (1)
  Local (6)

  [email protected] = [email protected] / 86400                      ' just get the number of days since epoch
  [email protected] = 1970+([email protected]/365)                   ' ball parking year, will not be accurate!

  [email protected] = 0
  For [email protected] = 1972 To [email protected] - 1 Step 4
    If ((([email protected]%4) = 0) * (([email protected]%100) # 0)) + (([email protected]%400) = 0) Then [email protected] = [email protected]+1
  Next

  [email protected] = 1970+(([email protected] - [email protected])/365)            ' calculating accurate current year by (x - extra leap days)
  [email protected] = (([email protected] - [email protected])%365)+1               ' if current year is leap, set indicator to 1
  [email protected] = ((([email protected]%4) = 0) * (([email protected]%100) # 0)) + (([email protected]%400) = 0)

  [email protected] = 0                               ' calculating current month
  For [email protected] = 0 To 11 Until [email protected] < ([email protected]+1)
    [email protected] = [email protected] + FUNC(_Monthdays ([email protected], [email protected]))
  Next
                                       ' calculating current date
  [email protected] = [email protected] - FUNC(_Monthdays ([email protected], [email protected]))
                                       ' Print [email protected], [email protected], [email protected], [email protected]
Return (Join (Str([email protected]), FUNC(_Format ([email protected], Dup("-"))), FUNC(_Format ([email protected] - [email protected], Dup("-")))))

_TimeStr                               ' convert epoch to time string
  Param (1)
Return (Join(Str(([email protected]%86400)/3600), FUNC(_Format (([email protected]%3600)/60, Dup(":"))), FUNC(_Format ([email protected]%60, Dup(":")))))

_Format    Param (2) : Return (Join (Iif ([email protected]<10, Join([email protected], "0"), [email protected]), Str ([email protected])))
_Monthdays Param (2) : Return ((([email protected] + ([email protected]<7)) % 2) + 30 - ((2 - [email protected]) * ([email protected]=1)))


#lang racket

(define (cube x) (* x x x))

;floor of cubic root
(define (cubic-root x)
  (let ([aprox (inexact->exact (round (expt x (/ 1 3))))])
    (if (> (cube aprox) x)
        (- aprox 1)
        aprox)))

(let loop ([p 1] [n 1])
  (let ()
    (define pairs
      (for*/list ([j (in-range 1 (add1 (cubic-root (quotient n 2))))]
                  [k (in-value (cubic-root (- n (cube j))))]
                  #:when (= n (+ (cube j) (cube k))))
        (cons j k)))
    (if (>= (length pairs) 2)
      (begin
        (printf "~a: ~a" p n)
        (for ([pair (in-list pairs)])
          (printf " = ~a^3 + ~a^3" (car pair) (cdr pair)))
          (newline)
        (when (< p 25)
          (loop (add1 p) (add1 n))))
      (loop p (add1 n)))))


constant @cu = (^Inf).map: { .³ }

sub MAIN ($start = 1, $end = 25) {
    my %taxi;
    my int $taxis = 0;
    my $terminate = 0;
    my int $max = 0;

    for 1 .. * -> $c1 {
        last if ?$terminate && ($terminate < $c1);
        for 1 .. $c1 -> $c2 {
            my $this = @cu[$c1] + @cu[$c2];
            %taxi{$this}.push: [$c2, $c1];
            if %taxi{$this}.elems == 2 {
                ++$taxis;
                $max max= $this;
            }
    	    $terminate = ceiling $max ** (1/3) if $taxis == $end and !$terminate;
        }
    }

    display( %taxi, $start, $end );

}

sub display (%this_stuff, $start, $end) {
    my $i = $start;
    printf "%4d %10d  =>\t%s\n", $i++, $_.key,
        (.value.map({ sprintf "%4d³ + %-s\³", |$_ })).join: ",\t"
        for %this_stuff.grep( { $_.value.elems > 1 } ).sort( +*.key )[$start-1..$end-1];
}


#
NOTES=$HOME/notes.txt
if [[ $# -eq 0 ]] ; then
  [[ -r  $NOTES ]] && more $NOTES
else
  date >> $NOTES
  echo "  $*" >> $NOTES
fi


Imports System.IO

Module Notes
    Function Main(ByVal cmdArgs() As String) As Integer
        Try
            If cmdArgs.Length = 0 Then
                Using sr As New StreamReader("NOTES.TXT")
                    Console.WriteLine(sr.ReadToEnd)
                End Using
            Else
                Using sw As New StreamWriter("NOTES.TXT", True)
                    sw.WriteLine(Date.Now.ToString())
                    sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs))
                End Using
            End If
        Catch
        End Try
    End Function
End Module


import "os" for Process
import "/ioutil" for File, FileUtil
import "/date" for Date

var dateFormatIn  = "yyyy|-|mm|-|dd|+|hh|:|MM"
var dateFormatOut = "yyyy|-|mm|-|dd| |hh|:|MM"
var args = Process.arguments
if (args.count == 0) {
    if (File.exists("NOTES.TXT")) System.print(File.read("NOTES.TXT"))
} else if (args.count == 1) {
    System.print("Enter the current date/time (MM/DD+HH:mm) plus at least one other argument.")
} else {
    var dateTime = Date.parse(args[0], dateFormatIn)
    var note = "\t" + args[1..-1].join(" ") + "\n"
    FileUtil.append("NOTES.TXT", dateTime.format(dateFormatOut) + "\n" + note)
}


/*REXX program displays the specified first (lowest) taxicab numbers (for three ranges).*/
parse arg  L.1  H.1      L.2 H.2      L.3 H.3 .  /*obtain optional arguments from the CL*/
   if L.1=='' | L.1==","  then L.1=   1          /*L1  is the low  part of 1st range.   */
   if H.1=='' | H.1==","  then H.1=  25          /*H1   "  "  high   "   "  "    "      */
   if L.2=='' | L.2==","  then L.2= 454          /*L2   "  "  low    "   " 2nd   "      */
   if H.2=='' | H.2==","  then H.2= 456          /*H2   "  "  high   "   "  "    "      */
   if L.3=='' | L.3==","  then L.3=2000          /*L3   "  "  low    "   " 3rd   "      */
   if H.3=='' | H.3==","  then H.3=2006          /*H3   "  "  high   "   "  "    "      */
mx= max(H.1,    H.2,    H.3)                     /*find how many taxicab numbers needed.*/
mx= mx   + mx % 10                               /*cushion;  compensate for the triples.*/
ww= length(mx) * 3;           w= ww % 2          /*widths used for formatting the output*/
numeric digits max(9, ww)                        /*prepare to use some larger numbers.  */
@.=.;    #= 0;     @@.= 0;    @and= "  ──and── " /*set some REXX vars and handy literals*/
$.=                                              /* [↓]  generate extra taxicab numbers.*/
    do j=1  until #>=mx;            C= j**3      /*taxicab numbers may not be in order. */
    !.j= C                                       /*use memoization for cube calculation.*/
      do k=1  for j-1;              s= C + !.k   /*define a whole bunch of cube sums.   */
      if @.s==.  then do;  @.s= j;  b.s= k       /*Cube not defined?   Then process it. */
                           iterate               /*define  @.S  and  B.S≡sum  of 2 cubes*/
                      end                        /* [↑]  define one cube sum at a time. */
      has= @@.s                                  /*has this number been defined before? */
      if has  then $.s= $.s @and U(j,'   +')U(k) /* ◄─ build a display string. [↓]      */
              else $.s= right(s,ww)  '───►'   U(@.s,"   +")U(b.s)   @and   U(j,'   +')U(k)
      @@.s= 1                                    /*mark taxicab number as a sum of cubes*/
      if has   then iterate                      /*S  is a triple (or sometimes better).*/
      #= # + 1;    #.#= s                        /*bump taxicab counter; define taxicab#*/
      end   /*k*/                                /* [↑]  build the cubes one─at─a─time. */
    end      /*j*/                               /* [↑]  complete with overage numbers. */
A.=
       do k=1  for mx;   _= #.k;    A.k= $._     /*re─assign disjoint $. elements to A. */
       end   /*k*/
call Esort  mx                                   /*sort taxicab #s with an exchange sort*/
       do grp=1  for 3;  call tell L.grp, H.grp  /*display the three grps of numbers. */
       end   /*grp*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell:  do t=arg(1)  to arg(2);    say right(t, 9)':'   A.t;     end;        say;    return
U:     return right(arg(1), w)'^3'arg(2)         /*right─justify a number,  append "^3" */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Esort: procedure expose A.; parse arg N;         h= N    /*Esort when items have blanks.*/
         do  while h>1;     h= h % 2
           do i=1  for N-h;           k=h + i;   j= i
              do forever;   parse var A.k xk .;  parse var A.j xj .;  if xk>=xj then leave
              _= A.j;       A.j= A.k; A.k= _             /*swap two elements of A. array*/
              if h>=j  then leave;    j=j - h;   k= k - h
              end   /*forever*/
           end      /*i*/
         end        /*while h>1*/;               return


include xpllib;         \Date and Time routines
int     I, NotesSize, Ch, CmdArgSize;
char    Notes(1_000_000), CmdArg(1000);
[\Read in notes.txt, if it exists
Trap(false);                    \disable abort on errors
FSet(FOpen("notes.txt", 0), ^i);
OpenI(3);
if GetErr = 0 then              \file exists
        [I:= 0;
        while GetErr = 0 do     \GetErr detects end-of-file
                [Notes(I):= ChIn(3);
                I:= I+1;
                ];
        NotesSize:= I-2;        \remove 2 EOFs
        ];
\Get command-line argument, if any, from command line
I:= 0;
loop    [Ch:= ChIn(8);
        if Ch = CR then quit;
        CmdArg(I):= Ch;
        I:= I+1;
        ];
CmdArg(I):= 0;          \terminate string
if I = 0 then           \no args, just display notes.txt
        for I:= 0 to NotesSize-1 do ChOut(0, Notes(I))
else    \open notes.txt for output and append CmdArg
        [FSet(FOpen("notes.txt", 1), ^o);
        OpenO(3);
        for I:= 0 to NotesSize-1 do ChOut(3, Notes(I));
        DateOut(3, GetDosDate);  ChOut(3, ^ );
        TimeOut(3, GetDosTime);  CrLf(3);
        ChOut(3, Tab);  Text(3, CmdArg);  CrLf(3);
        Close(3);
        ];
]


const notesName="NOTES.TXT";
args:=vm.arglist;
if (not args)
   { try{ File(notesName).read(*).text.print(); } catch{println("no file")} }
else{
   f:=File(notesName,"a+");
   f.writeln(Time.Date.ctime(),"\n\t",args.concat(" "));
   f.close();
}


# Project : Taxicab numbers

num = 0
for n = 1 to 500000
    nr = 0
    tax = []
    for m = 1 to 75
        for p = m + 1 to 75
            if n = pow(m, 3) + pow(p, 3)
               add(tax, m)
               add(tax, p)
               nr = nr + 1
            ok
        next
    next
    if nr > 1
       num = num + 1
       see "" + num + " " + n + " => " + tax[1] + "^3 + " + tax[2] + "^3" + ", "
       see "" + tax[3] + "^3 +" + tax[4] + "^3" + nl
       if num = 25
          exit
       ok
    ok
next
see "ok" + nl


def taxicab_number(nmax=1200)
  [*1..nmax].repeated_combination(2).group_by{|x,y| x**3 + y**3}.select{|k,v| v.size>1}.sort
end

t = [0] + taxicab_number

[*1..25, *2000...2007].each do |i|
  puts "%4d: %10d" % [i, t[i][0]] + t[i][1].map{|a| " = %4d**3 + %4d**3" % a}.join
end


use std::collections::HashMap;
use itertools::Itertools;

fn cubes(n: u64) -> Vec<u64> {
	let mut cube_vector = Vec::new();
	for i in 1..=n {
		cube_vector.push(i.pow(3));
	}
	cube_vector
}

fn main() {
	let c = cubes(1201);
	let it = c.iter().combinations(2);
	let mut m = HashMap::new();
	for x in it {
		let sum = x[0] + x[1];
		m.entry(sum).or_insert(Vec::new()).push(x)
	}

	let mut result = Vec::new();

	for (k,v) in m.iter() {
		if v.len() > 1 {
			result.push((k,v));
		}
	}

	result.sort();
	for f in result {
		println!("{:?}", f);
	}
}


import scala.collection.MapView
import scala.math.pow

implicit class Pairs[A, B]( p:List[(A, B)]) {
  def collectPairs: MapView[A, List[B]] = p.groupBy(_._1).view.mapValues(_.map(_._2)).filterNot(_._2.size<2)
}

// Make a sorted List of Taxi Cab Numbers. Limit it to the cube of 1200 because we know it's high enough.
val taxiNums = {
  (1 to 1200).toList            // Start with a sequential list of integers
    .combinations(2).toList     // Find all two number combinations
    .map {
      case a :: b :: nil => ((pow(a, 3) + pow(b, 3)).toInt, (a, b))
      case _ => 0 ->(0, 0)
    }                           // Turn the list into the sum of two cubes and
    //      remember what we started with, eg. 28->(1,3)
    .collectPairs               // Only keep taxi cab numbers with a duplicate
    .toList.sortBy(_._1)        // Sort the results
}

def output() : Unit = {
  println( "%20s".format( "Taxi Cab Numbers" ) )
  println( "%20s%15s%15s".format( "-"*20, "-"*15, "-"*15 ) )

  taxiNums.take(25) foreach {
    case (p, a::b::Nil) => println( "%20d\t(%d\u00b3 + %d\u00b3)\t\t(%d\u00b3 + %d\u00b3)".format(p,a._1,a._2,b._1,b._2) )
  }

  taxiNums.slice(1999,2007) foreach {
    case (p, a::b::Nil) => println( "%20d\t(%d\u00b3 + %d\u00b3)\t(%d\u00b3 + %d\u00b3)".format(p,a._1,a._2,b._1,b._2) )
  }
}


(import (scheme base)
        (scheme write)
        (srfi 1)        ; lists
        (srfi 69)       ; hash tables
        (srfi 132))     ; sorting

(define *max-n* 1500) ; let's go up to here, maximum for x and y
(define *numbers* (make-hash-table eqv?)) ; hash table for total -> list of list of pairs

(define (retrieve key) (hash-table-ref/default *numbers* key '()))

;; add all combinations to the hash table
(do ((i 1 (+ i 1)))
  ((= i *max-n*) )
  (do ((j (+ 1 i) (+ j 1)))
    ((= j *max-n*) )
    (let ((n (+ (* i i i) (* j j j))))
      (hash-table-set! *numbers* n
                       (cons (list i j) (retrieve n))))))

(define (display-number i key)
  (display (+ 1 i)) (display ": ")
  (display key) (display " -> ")
  (display (retrieve key)) (newline))

(let ((sorted-keys (list-sort <
                              (filter (lambda (key) (> (length (retrieve key)) 1))
                                      (hash-table-keys *numbers*)))))
  ;; first 25
  (for-each (lambda (i) (display-number i (list-ref sorted-keys i)))
            (iota 25))
  ;; 2000-2006
  (for-each (lambda (i) (display-number i (list-ref sorted-keys i)))
            (iota 7 1999))
  )


var (start=1, end=25) = ARGV.map{.to_i}...

func display (h, start, end) {
    var i = start
    for n in [h.grep {|_,v| v.len > 1 }.keys.sort_by{.to_i}[start-1 .. end-1]] {
        printf("%4d %10d  =>\t%s\n", i++, n,
            h{n}.map{ "%4d³ + %-s" % (.first, "#{.last}³") }.join(",\t"))
    }
}

var taxi = Hash()
var taxis = 0
var terminate = 0

for c1 (1..Inf) {
    if (0<terminate && terminate<c1) {
        display(taxi, start, end)
        break
    }
    var c = c1**3
    for c2 (1..c1) {
        var this = (c2**3 + c)
        taxi{this} := [] << [c2, c1]
        ++taxis if (taxi{this}.len == 2)
        if (taxis==end && !terminate) {
            terminate = taxi.grep{|_,v| v.len > 1 }.keys.map{.to_i}.max.root(3)
        }
    }
}


extension Array {
  func combinations(_ k: Int) -> [[Element]] {
    return Self._combinations(slice: self[startIndex...], k)
  }

  static func _combinations(slice: Self.SubSequence, _ k: Int) -> [[Element]] {
    guard k != 1 else {
      return slice.map({ [$0] })
    }

    guard k != slice.count else {
      return [slice.map({ $0 })]
    }

    let chopped = slice[slice.index(after: slice.startIndex)...]

    var res = _combinations(slice: chopped, k - 1).map({ [[slice.first!], $0].flatMap({ $0 }) })

    res += _combinations(slice: chopped, k)

    return res
  }
}

let cubes = (1...).lazy.map({ $0 * $0 * $0 })
let taxis =
  Array(cubes.prefix(1201))
    .combinations(2)
    .reduce(into: [Int: [[Int]]](), { $0[$1[0] + $1[1], default: []].append($1) })

let res =
  taxis
    .lazy
    .filter({ $0.value.count > 1 })
    .sorted(by: { $0.key < $1.key })
    .map({ ($0.key, $0.value) })
    .prefix(2006)

print("First 25 taxicab numbers:")
for taxi in res[..<25] {
  print(taxi)
}

print("\n2000th through 2006th taxicab numbers:")
for taxi in res[1999..<2006] {
  print(taxi)
}


package require Tcl 8.6

proc heappush {heapName item} {
    upvar 1 $heapName heap
    set idx [lsearch -bisect -index 0 -integer $heap [lindex $item 0]]
    set heap [linsert $heap [expr {$idx + 1}] $item]
}
coroutine cubesum apply {{} {
    yield
    set h {}
    set n 1
    while true {
	while {![llength $h] || [lindex $h 0 0] > $n**3} {
	    heappush h [list [expr {$n**3 + 1}] $n 1]
	    incr n
	}
	set h [lassign $h item]
	yield $item
	lassign $item s x y
	if {[incr y] < $x} {
	    heappush h [list [expr {$x**3 + $y**3}] $x $y]
	}
    }
}}
coroutine taxis apply {{} {
    yield
    set out {{0 0 0}}
    while true {
	set s [cubesum]
	if {[lindex $s 0] == [lindex $out end 0]} {
	    lappend out $s
	} else {
	    if {[llength $out] > 1} {yield $out}
	    set out [list $s]
	}
    }
}}

# Put a cache in front for convenience
variable taxis {}
proc taxi {n} {
    variable taxis
    while {$n > [llength $taxis]} {lappend taxis [taxis]}
    return [lindex $taxis [expr {$n-1}]]
}

set 3 "\u00b3"
for {set n 1} {$n <= 25} {incr n} {
    puts ${n}:[join [lmap t [taxi $n] {format " %d = %d$3 + %d$3" {*}$t}] ","]
}
for {set n 2000} {$n <= 2006} {incr n} {
    puts ${n}:[join [lmap t [taxi $n] {format " %d = %d$3 + %d$3" {*}$t}] ","]
}


Public Type tuple
    i As Variant
    j As Variant
    sum As Variant
End Type
Public Type tuple3
    i1 As Variant
    j1 As Variant
    i2 As Variant
    j2 As Variant
    i3 As Variant
    j3 As Variant
    sum As Variant
End Type
Sub taxicab_numbers()
    Dim i As Variant, j As Variant
    Dim k As Long
    Const MAX = 2019
    Dim p(MAX) As Variant
    Const bigMAX = (MAX + 1) * (MAX / 2)
    Dim big(1 To bigMAX) As tuple
    Const resMAX = 4400
    Dim res(1 To resMAX) As tuple3
    For i = 1 To MAX
        p(i) = CDec(i * i * i) 'convert Variant to Decimal
    Next i                     'wich hold numbers upto 10^28

    k = 1
    For i = 1 To MAX
        For j = i To MAX
            big(k).i = CDec(i)
            big(k).j = CDec(j)
            big(k).sum = CDec(p(i) + p(j))
            k = k + 1
        Next j
    Next i
    n = 1
    Quicksort big, LBound(big), UBound(big)
    For i = 1 To bigMAX - 1
        If big(i).sum = big(i + 1).sum Then
            res(n).i1 = CStr(big(i).i)
            res(n).j1 = CStr(big(i).j)
            res(n).i2 = CStr(big(i + 1).i)
            res(n).j2 = CStr(big(i + 1).j)
            If big(i + 1).sum = big(i + 2).sum Then
                res(n).i3 = CStr(big(i + 2).i)
                res(n).j3 = CStr(big(i + 2).j)
                i = i + 1
            End If
            res(n).sum = CStr(big(i).sum)
            n = n + 1
            i = i + 1
        End If
    Next i
    Debug.Print n - 1; " taxis"
    For i = 1 To 25
        With res(i)
            Debug.Print String$(4 - Len(CStr(i)), " "); i;
            Debug.Print String$(11 - Len(.sum), " "); .sum; " = ";
            Debug.Print String$(4 - Len(.i1), " "); .i1; "^3 +";
            Debug.Print String$(4 - Len(.j1), " "); .j1; "^3 = ";
            Debug.Print String$(4 - Len(.i2), " "); .i2; "^3 +";
            Debug.Print String$(4 - Len(.j2), " "); .j2; "^3"
        End With
    Next i
    Debug.Print
    For i = 2000 To 2006
        With res(i)
            Debug.Print String$(4 - Len(CStr(i)), " "); i;
            Debug.Print String$(11 - Len(.sum), " "); .sum; " = ";
            Debug.Print String$(4 - Len(.i1), " "); .i1; "^3 +";
            Debug.Print String$(4 - Len(.j1), " "); .j1; "^3 = ";
            Debug.Print String$(4 - Len(.i2), " "); .i2; "^3 +";
            Debug.Print String$(4 - Len(.j2), " "); .j2; "^3"
        End With

    Next i
    Debug.Print
    For i = 1 To resMAX
        If res(i).i3 <> "" Then
            With res(i)
                Debug.Print String$(4 - Len(CStr(i)), " "); i;
                Debug.Print String$(11 - Len(.sum), " "); .sum; " = ";
                Debug.Print String$(4 - Len(.i1), " "); .i1; "^3 +";
                Debug.Print String$(4 - Len(.j1), " "); .j1; "^3 = ";
                Debug.Print String$(4 - Len(.i2), " "); .i2; "^3 +";
                Debug.Print String$(4 - Len(.j2), " "); .j2; "^3";
                Debug.Print String$(4 - Len(.i3), " "); .i3; "^3 +";
                Debug.Print String$(4 - Len(.j3), " "); .j3; "^3"
            End With
        End If
    Next i
End Sub
Sub Quicksort(vArray() As tuple, arrLbound As Long, arrUbound As Long)
    'https://wellsr.com/vba/2018/excel/vba-quicksort-macro-to-sort-arrays-fast/
    'Sorts a one-dimensional VBA array from smallest to largest
    'using a very fast quicksort algorithm variant.
    'Adapted to multidimensions/typedef
    Dim pivotVal As Variant
    Dim vSwap    As tuple
    Dim tmpLow   As Long
    Dim tmpHi    As Long

    tmpLow = arrLbound
    tmpHi = arrUbound
    pivotVal = vArray((arrLbound + arrUbound) \ 2).sum

    While (tmpLow <= tmpHi) 'divide
        While (vArray(tmpLow).sum < pivotVal And tmpLow < arrUbound)
            tmpLow = tmpLow + 1
        Wend

        While (pivotVal < vArray(tmpHi).sum And tmpHi > arrLbound)
            tmpHi = tmpHi - 1
        Wend

        If (tmpLow <= tmpHi) Then
             vSwap.i = vArray(tmpLow).i
             vSwap.j = vArray(tmpLow).j
             vSwap.sum = vArray(tmpLow).sum
             vArray(tmpLow).i = vArray(tmpHi).i
             vArray(tmpLow).j = vArray(tmpHi).j
             vArray(tmpLow).sum = vArray(tmpHi).sum
             vArray(tmpHi).i = vSwap.i
             vArray(tmpHi).j = vSwap.j
             vArray(tmpHi).sum = vSwap.sum
             tmpLow = tmpLow + 1
             tmpHi = tmpHi - 1
        End If
    Wend

    If (arrLbound < tmpHi) Then Quicksort vArray, arrLbound, tmpHi 'conquer
    If (tmpLow < arrUbound) Then Quicksort vArray, tmpLow, arrUbound 'conquer
End Sub


Imports System.Text

Module Module1

    Function GetTaxicabNumbers(length As Integer) As IDictionary(Of Long, IList(Of Tuple(Of Integer, Integer)))
        Dim sumsOfTwoCubes As New SortedList(Of Long, IList(Of Tuple(Of Integer, Integer)))

        For i = 1 To Integer.MaxValue - 1
            For j = 1 To Integer.MaxValue - 1
                Dim sum = CLng(Math.Pow(i, 3) + Math.Pow(j, 3))

                If Not sumsOfTwoCubes.ContainsKey(sum) Then
                    sumsOfTwoCubes.Add(sum, New List(Of Tuple(Of Integer, Integer)))
                End If

                sumsOfTwoCubes(sum).Add(Tuple.Create(i, j))

                If j >= i Then
                    Exit For
                End If
            Next

            REM Found that you need to keep going for a while after the length, because higher i values fill in gaps
            If sumsOfTwoCubes.AsEnumerable.Count(Function(t) t.Value.Count >= 2) >= length * 1.1 Then
                Exit For
            End If
        Next

        Dim values = (From t In sumsOfTwoCubes Where t.Value.Count >= 2 Select t) _
            .Take(2006) _
            .ToDictionary(Function(u) u.Key, Function(u) u.Value)
        Return values
    End Function

    Sub PrintTaxicabNumbers(values As IDictionary(Of Long, IList(Of Tuple(Of Integer, Integer))))
        Dim i = 1
        For Each taxicabNumber In values.Keys
            Dim output As New StringBuilder
            output.AppendFormat("{0,10}" + vbTab + "{1,4}", i, taxicabNumber)

            For Each numbers In values(taxicabNumber)
                output.AppendFormat(vbTab + "= {0}^3 + {1}^3", numbers.Item1, numbers.Item2)
            Next

            If i <= 25 OrElse (i >= 2000 AndAlso i <= 2006) Then
                Console.WriteLine(output.ToString)
            End If

            i += 1
        Next
    End Sub

    Sub Main()
        Dim taxicabNumbers = GetTaxicabNumbers(2006)
        PrintTaxicabNumbers(taxicabNumbers)
    End Sub

End Module


import "/sort" for Sort
import "/fmt" for Fmt

var cubesSum = {}
var taxicabs = []

for (i in 1..1199) {
    for (j in i+1..1200) {
        var sum = i*i*i + j*j*j
        if (!cubesSum[sum]) {
            cubesSum[sum] = [i, j]
        } else {
            taxicabs.add([sum, cubesSum[sum], [i, j]])
        }
    }
}
var cmp = Fn.new { |a, b| (a[0] - b[0]).sign }
Sort.quick(taxicabs, 0, taxicabs.count-1, cmp)
// remove those numbers which have additional pairs of cubes
for (i in taxicabs.count-2..0) {
    if (taxicabs[i][0] == taxicabs[i+1][0]) taxicabs.removeAt(i+1)
}

System.print("The first 25 taxicab numbers are:")
for (i in 1..25) {
    var t = taxicabs[i-1]
    Fmt.lprint("$2d: $,7d = $2d³ + $2d³ = $2d³ + $2d³", [i, t[0], t[1][0], t[1][1], t[2][0], t[2][1]])
}

System.print("\nThe 2,000th to 2,006th taxicab numbers are:")
for (i in 2000..2006) {
    var t = taxicabs[i-1]
    Fmt.lprint("$,5d: $,13d = $3d³ + $,5d³ = $3d³ + $,5d³", [i, t[0], t[1][0], t[1][1], t[2][0], t[2][1]])
}


int N, I, J, SI, SJ, Count, Tally;
[Count:= 0;  N:= 0;
repeat  Tally:= 0;
        I:= 1;
        repeat  J:= I+1;
                repeat  if N = I*I*I + J*J*J then
                            [Tally:= Tally+1;
                            if Tally >= 2 then
                                [Count:= Count+1;
                                IntOut(0, Count);  Text(0, ": ");
                                IntOut(0, N);  Text(0, " = ");
                                IntOut(0, SI); Text(0, "^^3 + ");
                                IntOut(0, SJ); Text(0, "^^3 = ");
                                IntOut(0, I);  Text(0, "^^3 + ");
                                IntOut(0, J);  Text(0, "^^3");
                                CrLf(0);
                                J:= 1000;  I:= J;
                                ];
                            SI:= I;  SJ:= J;
                            ];
                        J:= J+1;
                until   I*I*I + J*J*J > N;
                I:= I+1;
        until   I*I*I*2 > N;
        N:= N+1;
until   Count >= 25;
]


fcn taxiCabNumbers{
   const HeapSZ=0d5_000_000;
   iCubes:=[1..120].apply("pow",3);
   sum2cubes:=Data(HeapSZ).fill(0);  // BFheap of 1 byte zeros
   taxiNums:=List();
   foreach i,i3 in ([1..].zip(iCubes)){
      foreach j,j3 in ([i+1..].zip(iCubes[i,*])){
         ij3:=i3+j3;
	 if(z:=sum2cubes[ij3]){
	    taxiNums.append(T(ij3,
		z,(ij3-z.pow(3)).toFloat().pow(1.0/3).round().toInt(),
		i,j));
	 }
	 else sum2cubes[ij3]=i;
      }
   }
   taxiNums.sort(fcn([(a,_)],[(b,_)]){ a<b })
}


10 DIM f(1625): REM populating a cube table at the start will be faster than computing the cubes on the fly
20 FOR x=1 TO 1625
30 LET f(x)=x*x*x: REM x*x*x rather than x^3 as the ZX Spectrum's exponentiation function is legendarily slow
40 NEXT x
50 LET c=0
60 FOR x=1 TO 4294967295: REM the highest number the ZX Spectrum Basic can accurately hold internally; floor (cuberoot max)=1625, hence the table limit
70 LET k=0
80 FOR m=1 TO 1625
90 FOR n=m+1 TO 1625
100 IF f(m)+f(n)=x THEN GOTO 160
110 IF f(n)>=x THEN LET n=1625: REM overshot, break out of the loop
120 IF f(m)>=x THEN LET m=1625
130 NEXT n
140 NEXT m
150 NEXT x
160 IF k=1 THEN LET q=m: LET r=n: GO TO 230: REM got one!
170 LET o=m
180 LET p=n
190 LET k=1
200 NEXT n
210 NEXT m
220 NEXT x
230 LET c=c+1
240 IF c>25 AND c<2000 THEN GO TO 330
250 LET t$="": REM convert number to string; while ZX Spectrum Basic can store all the digits of integers up to 2^32-1...
260 LET t=INT (x/100000): REM ...it will resort to scientific notation trying to display any more than eight digits
270 LET b=x-t*100000
280 IF t=0 THEN GO TO 300: REM omit leading zero
290 LET t$=STR$ t
300 LET t$=t$+STR$ b
310 PRINT c;":";t$;"=";q;"^3+";r;"^3=";o;"^3+";p;"^3"
320 POKE 23692,10: REM suppress "scroll?" prompt when screen fills up at c=22
330 IF c=2006 THEN LET x=4294967295: LET n=1625: LET m=1625
340 NEXT n
350 NEXT m
360 NEXT x


F sylverster(lim)
   V result = [BigInt(2)]
   L 2..lim
      result.append(product(result) + 1)
   R result

V l = sylverster(10)
print(‘First 10 terms of the Sylvester sequence:’)
L(item) l
   print(item)

V s = 0.0
L(item) l
   s += 1 / Float(item)
print("\nSum of the reciprocals of the first 10 terms: #.17".format(s))


BEGIN # calculate elements of Sylvestor's Sequence                         #
    PR precision 200 PR # set the number of digits for LONG LONG modes     #
    # returns an array set to the forst n elements of Sylvestor's Sequence #
    #    starting from 2, the elements are the product of the previous     #
    #                     elements plus 1                                  #
    OP SYLVESTOR = ( INT n )[]LONG LONG INT:
       BEGIN
           [ 1 : n ]LONG LONG INT result;
           LONG LONG INT product := 2;
           result[ 1 ] := 2;
           FOR i FROM 2 TO n DO
               result[ i ] := product + 1;
               product *:= result[ i ]
           OD;
           result
       END;
    # find the first 10 elements of Sylvestor's Seuence #
    []LONG LONG INT seq = SYLVESTOR 10;
    # show the sequence and sum the reciprocals #
    LONG LONG REAL reciprocal sum := 0;
    FOR i FROM LWB seq TO UPB seq DO
        print( ( whole( seq[ i ], 0 ), newline ) );
        reciprocal sum +:= 1 / seq[ i ]
    OD;
    print( ( "Sum of reciprocals: ", reciprocal sum, newline ) )
END


sylvester: function [lim][
    result: new [2]
    loop 2..lim 'x [
        'result ++ inc fold result .seed:1 [a b][a * b]
    ]
    return result
]
lst: sylvester 10

print "First 10 terms of the Sylvester sequence:"
print lst
print ""

sumRep: round sum map lst => [1 // &]

print "Sum of the reciprocals of the first 10 items:"
print sumRep


# syntax: GAWK --bignum -f SYLVESTERS_SEQUENCE.AWK
BEGIN {
    start = 1
    stop = 10
    for (i=start; i<=stop; i++) {
      sylvester = (i == 1) ? 2 : sylvester*sylvester-sylvester+1
      printf("%2d: %d\n",i,sylvester)
      sum += 1 / sylvester
    }
    printf("\nSylvester sequence %d-%d: sum of reciprocals %30.28f\n",start,stop,sum)
    exit(0)
}


PRINT "10 primeros términos de la sucesión de sylvester:"
PRINT

LET suma = 0
FOR i = 1 TO 10
    IF i = 1 THEN
       LET sylvester = 2
    ELSE
       LET sylvester = sylvester*sylvester-sylvester+1
    END IF
    PRINT i; ": "; sylvester
    LET suma = suma + 1 / sylvester
NEXT i

PRINT
PRINT "suma de sus recíprocos: "; suma
END


#include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>

using integer = boost::multiprecision::cpp_int;
using rational = boost::rational<integer>;

integer sylvester_next(const integer& n) {
    return n * n - n + 1;
}

int main() {
    std::cout << "First 10 elements in Sylvester's sequence:\n";
    integer term = 2;
    rational sum = 0;
    for (int i = 1; i <= 10; ++i) {
        std::cout << std::setw(2) << i << ": " << term << '\n';
        sum += rational(1, term);
        term = sylvester_next(term);
    }
    std::cout << "Sum of reciprocals: " << sum << '\n';
}


// Sylvester's sequence: Nigel Galloway. June 7th., 2021
let S10=Seq.unfold(fun(n,g)->printfn "*%A %A" n g; Some(n,(n*g+1I,n*g) ) )(2I,1I)|>Seq.take 10|>List.ofSeq
S10|>List.iteri(fun n g->printfn "%2d -> %A" (n+1) g)
let n,g=S10|>List.fold(fun(n,g) i->(n*i+g,g*i))(0I,1I) in printfn "\nThe sum of the reciprocals of S10 is \n%A/\n%A" n g


USING: io kernel lists lists.lazy math prettyprint ;

: lsylvester ( -- list ) 2 [ dup sq swap - 1 + ] lfrom-by ;

"First 10 elements of Sylvester's sequence:" print
10 lsylvester ltake dup [ . ] leach nl

"Sum of the reciprocals of first 10 elements:" print
0 [ recip + ] foldl .


package main

import (
    "fmt"
    "math/big"
)

func main() {
    one := big.NewInt(1)
    two := big.NewInt(2)
    next := new(big.Int)
    sylvester := []*big.Int{two}
    prod := new(big.Int).Set(two)
    count := 1
    for count < 10 {
        next.Add(prod, one)
        sylvester = append(sylvester, new(big.Int).Set(next))
        count++
        prod.Mul(prod, next)
    }
    fmt.Println("The first 10 terms in the Sylvester sequence are:")
    for i := 0; i < 10; i++ {
        fmt.Println(sylvester[i])
    }

    sumRecip := new(big.Rat)
    for _, s := range sylvester {
        sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))
    }
    fmt.Println("\nThe sum of their reciprocals as a rational number is:")
    fmt.Println(sumRecip)
    fmt.Println("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
    fmt.Println(sumRecip.FloatString(211))
}


sylvester :: [Integer]
sylvester = map s [0 ..]
  where
    s 0 = 2
    s n = succ $ foldr ((*) . s) 1 [0 .. pred n]

main :: IO ()
main = do
  putStrLn "First 10 elements of Sylvester's sequence:"
  putStr $ unlines $ map show $ take 10 sylvester

  putStr "\nSum of reciprocals by sum over map: "
  print $ sum $ map ((1 /) . fromInteger) $ take 10 sylvester

  putStr "Sum of reciprocals by fold: "
  print $ foldr ((+) . (1 /) . fromInteger) 0 $ take 10 sylvester


# Generate the sylvester integers:
def sylvester:
  foreach range(0; infinite) as $i ({prev: 1, product: 1};
    .product *= .prev
    | .prev = .product + 1;
    .prev);


sylvester(n) = (n == 1) ? big"2" : prod(sylvester, 1:n-1) + big"1"

foreach(n -> println(rpad(n, 3), " =>  ", sylvester(n)), 1:10)

println("Sum of reciprocals of first 10: ", sum(big"1.0" / sylvester(n) for n in 1:10))


import sequtils
import bignum

proc sylverster(lim: Positive): seq[Int] =
  result.add(newInt(2))
  for _ in 2..lim:
    result.add result.foldl(a * b) + 1

let list = sylverster(10)
echo "First 10 terms of the Sylvester sequence:"
for item in list: echo item

var sum = newRat()
for item in list: sum += newRat(1, item)
echo "\nSum of the reciprocals of the first 10 terms: ", sum.toFloat


use strict;
use warnings;
use feature 'say';
use List::Util 'reduce';
use Math::AnyNum ':overload';
local $Math::AnyNum::PREC = 845;

my(@S,$sum);
push @S, 1 + reduce { $a * $b } @S for 0..10;
shift @S;
$sum += 1/$_ for @S;

say "First 10 elements of Sylvester's sequence: @S";
say "\nSum of the reciprocals of first 10 elements: " . float $sum;


atom n, rn = 0,
     lim = power(2,iff(machine_bits()=32?53:64))
for i=1 to 10 do
    n = iff(i=1?2:n*n-n+1)
    printf(1,iff(n<=lim?"%d: %d\n":"%d: %g\n"),{i,n})
    rn += 1/n
end for
printf(1,"sum of reciprocals: %g\n",{rn})


100H: /* CALCULATE ELEMENTS OF SYLVESTOR'S SEQUENCE                          */

   BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL                      */
      DECLARE FN BYTE, ARG ADDRESS;
      GOTO 5;
   END BDOS;
   PRINT$CHAR:   PROCEDURE( C ); DECLARE C BYTE;    CALL BDOS( 2, C ); END;
   PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
   DECLARE PRINT$NL LITERALLY 'PRINT$STRING( .( 0DH, 0AH, ''$'' ) )';

   DECLARE LONG$INTEGER  LITERALLY '(201)BYTE';
   DECLARE DIGIT$BASE    LITERALLY '10';

   /* PRINTS A LONG INTEGER                                                  */
   PRINT$LONG$INTEGER: PROCEDURE( N$PTR );
      DECLARE N$PTR ADDRESS;
      DECLARE N BASED N$PTR LONG$INTEGER;
      DECLARE ( D, F ) BYTE;
      F = N( 0 );
      DO D = 1 TO N( 0 );
         CALL PRINT$CHAR( N( F ) + '0' );
         F = F - 1;
      END;
   END PRINT$LONG$INTEGER;
   /* IMPLEMENTS LONG MULTIPLICATION, C IS SET TO A * B                      */
   /*     C CAN BE THE SAME LONG$INTEGER AS A OR B                           */
   LONG$MULTIPLY: PROCEDURE( A$PTR, B$PTR, C$PTR );
      DECLARE ( A$PTR, B$PTR, C$PTR ) ADDRESS;
      DECLARE ( A BASED A$PTR, B BASED B$PTR, C BASED C$PTR ) LONG$INTEGER;
      DECLARE MRESULT LONG$INTEGER;
      DECLARE RPOS    BYTE;

      /* MULTIPLIES THE LONG INTEGER IN B BY THE INTEGER A, THE RESULT       */
      /*     IS ADDED TO C, STARTING FROM DIGIT START                        */
      /*     OVERFLOW IS IGNORED                                             */
      MULTIPLY$ELEMENT: PROCEDURE( A, B$PTR, C$PTR, START );
         DECLARE ( B$PTR, C$PTR )                 ADDRESS;
         DECLARE ( A, START )                     BYTE;
         DECLARE ( B BASED B$PTR, C BASED C$PTR ) LONG$INTEGER;
         DECLARE ( CDIGIT, D$CARRY, BPOS, CPOS )  BYTE;
         D$CARRY = 0;
         CPOS    = START;
         DO BPOS = 1 TO B( 0 );
            CDIGIT = C( CPOS ) + ( A * B( BPOS ) ) + D$CARRY;
            IF CDIGIT < DIGIT$BASE THEN D$CARRY = 0;
            ELSE DO;
               /* HAVE DIGITS TO CARRY                                       */
               D$CARRY = CDIGIT  /  DIGIT$BASE;
               CDIGIT  = CDIGIT MOD DIGIT$BASE;
            END;
            C( CPOS ) = CDIGIT;
            CPOS = CPOS + 1;
         END;
         C( CPOS ) = D$CARRY;
         /* REMOVE LEADING ZEROS BUT IF THE NUMBER IS 0, KEEP THE FINAL 0    */
         DO WHILE( CPOS > 1 AND C( CPOS ) = 0 );
            CPOS = CPOS - 1;
         END;
         C( 0 ) = CPOS;
      END MULTIPLY$ELEMENT ;

      /* THE RESULT WILL BE COMPUTED IN MRESULT, ALLOWING A OR B TO BE C     */
      DO RPOS = 1 TO LAST( MRESULT ); MRESULT( RPOS ) = 0; END;
      /* MULTIPLY BY EACH DIGIT AND ADD TO THE RESULT                        */
      DO RPOS = 1 TO A( 0 );
         IF A( RPOS ) <> 0 THEN DO;
            CALL MULTIPLY$ELEMENT( A( RPOS ), B$PTR, .MRESULT, RPOS );
         END;
      END;
      /* RETURN THE RESULT IN C                                              */
      DO RPOS = 0 TO MRESULT( 0 ); C( RPOS ) = MRESULT( RPOS ); END;
   END;
   /* ADDS THE INTEGER A TO THE LONG$INTEGER N                               */
   ADD$BYTE$TO$LONG$INTEGER: PROCEDURE( A, N$PTR );
      DECLARE A BYTE, N$PTR ADDRESS;
      DECLARE N BASED N$PTR LONG$INTEGER;
      DECLARE ( D, D$CARRY, DIGIT ) BYTE;
      D       = 1;
      D$CARRY = A;
      DO WHILE( D$CARRY > 0 );
         DIGIT = N( D ) + D$CARRY;
         IF DIGIT < DIGIT$BASE THEN DO;
            N( D )  = DIGIT;
            D$CARRY = 0;
            END;
         ELSE DO;
             D$CARRY = DIGIT  /  DIGIT$BASE;
             N( D )  = DIGIT MOD DIGIT$BASE;
             D       = D + 1;
             IF D > N( 0 ) THEN DO;
                /* THE NUMBER NOW HAS AN EXTRA DIGIT                         */
                N( 0 )  = D;
                N( D )  = D$CARRY;
                D$CARRY = 0;
             END;
         END;
      END;
   END ADD$BYTE$TO$LONG$INTEGER;
   /* FIND THE FIRST 10 ELEMENTS OF SYLVESTOR'S SEQUENCE                     */
   DECLARE ( SEQ$ELEMENT, PRODUCT ) LONG$INTEGER;
   DECLARE ( I, D )                 BYTE;
   DO D = 2 TO LAST( PRODUCT     ); PRODUCT(     D ) = 0; END;
   DO D = 2 TO LAST( SEQ$ELEMENT ); SEQ$ELEMENT( D ) = 0; END;
   SEQ$ELEMENT( 0 ) = 1; /* THE FIRST SEQUENCE ELEMENT HAS 1 DIGIT...        */
   SEQ$ELEMENT( 1 ) = 2; /* WHICH IS 2                                       */
   PRODUCT(     0 ) = 1;
   PRODUCT(     1 ) = 2;
   CALL PRINT$LONG$INTEGER( .SEQ$ELEMENT );     /* SHOW ELEMENT 1            */
   CALL PRINT$NL;
   DO I = 2 TO 9;
      DO D = 0 TO PRODUCT( 0 ); SEQ$ELEMENT( D ) = PRODUCT( D ); END;
      CALL ADD$BYTE$TO$LONG$INTEGER( 1, .SEQ$ELEMENT );
      CALL PRINT$LONG$INTEGER( .SEQ$ELEMENT );
      CALL LONG$MULTIPLY( .SEQ$ELEMENT, .PRODUCT, .PRODUCT );
      CALL PRINT$NL;
   END;
   /* THE FINAL ELEMENT IS THE PRODUCT PLUS 1                                */
   CALL ADD$BYTE$TO$LONG$INTEGER( 1, .PRODUCT );
   CALL PRINT$LONG$INTEGER( .PRODUCT );
   CALL PRINT$NL;
EOF


sylvesters_sequence(N, S, R):-
    sylvesters_sequence(N, S, 2, R, 0).

sylvesters_sequence(0, [X], X, R, S):-
    !,
    R is S + 1 rdiv X.
sylvesters_sequence(N, [X|Xs], X, R, S):-
    Y is X * X - X + 1,
    M is N - 1,
    T is S + 1 rdiv X,
    sylvesters_sequence(M, Xs, Y, R, T).

main:-
    sylvesters_sequence(9, Sequence, Sum),
    writeln('First 10 elements in Sylvester\'s sequence:'),
    forall(member(S, Sequence), writef('%t\n', [S])),
    N is numerator(Sum),
    D is denominator(Sum),
    writef('\nSum of reciprocals: %t / %t\n', [N, D]).


'''Sylvester's sequence'''

from functools import reduce
from itertools import count, islice

# sylvester :: [Int]
def sylvester():
    '''Non-finite stream of the terms
       of Sylvester's sequence.
       (OEIS A000058)
    '''
    def go(n):
        return 1 + reduce(
            lambda a, x: a * go(x),
            range(0, n),
            1
        ) if 0 != n else 2

    return map(go, count(0))

# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''First terms, and sum of reciprocals.'''

    print("First 10 terms of OEIS A000058:")
    xs = list(islice(sylvester(), 10))
    print('\n'.join([
        str(x) for x in xs
    ]))

    print("\nSum of the reciprocals of the first 10 terms:")
    print(
        reduce(lambda a, x: a + 1 / x, xs, 0)
    )

# MAIN ---
if __name__ == '__main__':
    main()


[ $ "bigrat.qky" loadfile ] now!

' [ 2 ] 9 times [ dup -1 peek dup 2 ** swap - 1+ join ]

dup witheach [ echo cr ] cr

0 n->v rot witheach [ n->v 1/v v+ ] 222 point$ echo$


my @S = {1 + [*] @S[^($++)]} … *;

put 'First 10 elements of Sylvester\'s sequence: ', @S[^10];

say "\nSum of the reciprocals of first 10 elements: ", sum @S[^10].map: { FatRat.new: 1, $_ };


/*REXX pgm finds N terms of the Sylvester's sequence & the sum of the their reciprocals.*/
parse arg n .                                    /*obtain optional argument from the CL.*/
if n=='' | n==","  then n= 10                    /*Not specified?  Then use the default.*/
numeric digits max(9, 2**(n-7) * 13 + 1)         /*calculate how many dec. digs we need.*/
@.0= 2                                           /*the value of the 1st Sylvester number*/
$= 0
        do j=0  for n;      jm= j - 1            /*calculate the Sylvester sequence.    */
        if j>0  then @.j= @.jm**2 - @.jm + 1     /*calculate  a  Sylvester sequence num.*/
        say 'Sylvester('j") ──► "   @.j          /*display the Sylvester index & number.*/
        $= $   +   1 / @.j                       /*add its reciprocal to the recip. sum.*/
        end   /*j*/
say                                              /*stick a fork in it,  we're all done. */
numeric digits digits() - 1
say 'sum of the first '   n   " reciprocals using"   digits()   'decimal digits: '   $ / 1


def sylvester(n) = (1..n).reduce(2){|a| a*a - a + 1 }

(0..9).each {|n| puts "#{n}: #{sylvester n}"  }
puts "
Sum of reciprocals of first 10 terms:
#{(0..9).sum{|n| 1.0r / sylvester(n)}.to_f }"


(define sylvester
  (lambda (x)
    (if (= x 1)
      2
      (let ((n (sylvester (- x 1)))) (- (* n n) n -1)))))
(define list (map sylvester '(1 2 3 4 5 6 7 8 9 10)))
(print list)
(newline)
(print (apply + (map / list)))


$ include "seed7_05.s7i";
  include "bigint.s7i";
  include "bigrat.s7i";

const func bigInteger: nextSylvester (in bigInteger: prev) is
  return prev * prev - prev + 1_;

const proc: main is func
  local
    var bigInteger: number is 2_;
    var bigRational: reciprocalSum is 0_ / 1_;
    var integer: n is 0;
  begin
    writeln("First 10 elements of Sylvester's sequence:");
    for n range 1 to 10 do
      writeln(number);
      reciprocalSum +:= 1_ / number;
      number := nextSylvester(number);
    end for;
    writeln("\nSum of the reciprocals of the first 10 elements:");
    writeln(reciprocalSum digits 210);
  end func;


func sylvester_sequence(n) {
    1..n -> reduce({|a| a*(a-1) + 1 }, 2)
}

say "First 10 terms in Sylvester's sequence:"
10.of(sylvester_sequence).each_kv{|k,v| '%2s: %s' % (k,v) -> say }

say "\nSum of reciprocals of first 10 terms: "
say 10.of(sylvester_sequence).sum {|n| 1/n }.as_dec(230)


import BigNumber

func sylvester(n: Int) -> BInt {
  var a = BInt(2)

  for _ in 0..<n {
    a = a * a - a + 1
  }

  return a
}

var sum = BDouble(0)

for n in 0..<10 {
  let syl = sylvester(n: n)
  sum += BDouble(1) / BDouble(syl)
  print(syl)
}

print("Sum of the reciprocals of first ten in sequence: \(sum)")


module main;
  integer i;
  real suma, num;

  initial begin
    $display("10 primeros términos de la sucesión de sylvester:");
    $display("");

    suma = 0;
    num = 0;
    for(i=1; i<=10; i=i+1) begin
        if (i==1) num = 2;
        else      num = num * num - num + 1;

        $display(i, ": ", num);
        suma = suma + 1 / num;
    end

    $display("");
    $display("suma de sus recíprocos: ", suma);
    $finish ;
  end
endmodule


import "/big" for BigInt, BigRat

var sylvester = [BigInt.two]
var prod = BigInt.two
var count = 1
while (true) {
    var next = prod + 1
    sylvester.add(next)
    count = count + 1
    if (count == 10) break
    prod = prod * next
}
System.print("The first 10 terms in the Sylvester sequence are:")
System.print(sylvester.join("\n"))

var sumRecip = sylvester.reduce(BigRat.zero) { |acc, s| acc + BigRat.new(1, s) }
System.print("\nThe sum of their reciprocals as a rational number is:")
System.print (sumRecip)
System.print("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
System.print(sumRecip.toDecimal(211))


package Synchronous_Concurrent is
   task Printer is
      entry Put(Item : in String);
      entry Get_Count(Count : out Natural);
   end Printer;
end Synchronous_Concurrent;


monitor Queue {
    var items = []
    public function put (item) {
        items.append (item)
        notify()
    }

    public function get() {
        while (items.size() == 0) {
            wait()
        }
        var item = items[0]
        items <<= 1
        return item
    }

    public function close {
        items.append (none)
    }
}

thread reader (queue) {
    var numlines = 0
    for (;;) {
        var line = queue.get()
        if (typeof(line) == "none") {
            break
        }
        print (line)
        numlines++
    }
    println ("Number of lines: " + numlines)
}

thread writer (queue, lines) {
    foreach line lines {
        queue.put (line)
    }
    queue.close()
}

var queue = new Queue()
var lines = readfile ("input.txt")
var r = reader(queue)
var w = writer(queue, lines)

join (r)
join (w)


(
  STRING line;
  INT count := 0, errno;
  BOOL input complete := FALSE;
  SEMA output throttle = LEVEL 0, input throttle = LEVEL 1;

  FILE input txt;
  errno := open(input txt, "input.txt", stand in channel);

  PROC call back done = (REF FILE f) BOOL: ( input complete := TRUE );
  on logical file end(input txt, call back done);

  PAR (
    WHILE
      DOWN input throttle;
      get(input txt,(line, new line));
      UP output throttle;
      NOT input complete
    DO
      count+:=1
    OD
  ,
    WHILE
      DOWN output throttle;
      NOT input complete
    DO
      print((line, new line));
      UP input throttle
    OD
  );
  print((count))
)


// This is a BCPL implementation of the Rosettacode synchronous
// concurrency test using BCPL coroutines and a coroutine implementation
// of a Occum-style channels.
// BCPL is freely available from www.cl.cam.ac.uk/users/mr10

SECTION "coinout"

GET "libhdr.h"

GLOBAL {
  tracing: ug
}

LET start() = VALOF
{ LET argv = VEC 50
  LET in_co, out_co = 0, 0
  LET channel = 0
  LET filename = "input.txt"

  UNLESS rdargs("-f,-t/S", argv, 50) DO
  { writef("Bad arguments for coinout*n")
    RESULTIS 0
  }

  IF argv!0 DO filename := argv!0  // -f     the source file
  tracing := argv!1                // -t/S   tracing option

  in_co  := initco(infn,  500, @channel)
  out_co := initco(outfn, 500, @channel)

  UNLESS in_co & out_co DO
  { writef("Trouble creating the coroutines*n")
    GOTO fin
  }

  IF tracing DO writef("*nBoth in and out coroutines created*n*n")

  callco(in_co, filename)

fin:
  IF in_co  DO deleteco(in_co)
  IF out_co DO deleteco(out_co)

  IF tracing DO writef("Both in and out coroutines deleted*n*n")

  RESULTIS 0
}

AND readline(line) = VALOF
{ LET ch, i = 0, 0
  line%0 := 0

  { ch := rdch()
    IF ch=endstreamch RESULTIS FALSE
    i := i+1
    line%0, line%i := i, ch
    IF ch='*n' | i=255 BREAK
  } REPEAT

  RESULTIS TRUE
}

AND infn(args) BE
{ LET channelptr = args!0
  LET name = cowait()  // Get the file name
  LET instream = findinput(name)
  LET line = VEC 256/bytesperword

  UNLESS instream DO
  { writef("*nTrouble with file: %s*n", name)
    RETURN
  }

  selectinput(instream)

  { LET ok = readline(line)
    UNLESS ok BREAK
    IF tracing DO
      writef("inco:  Sending a line to outco*n")
    cowrite(channelptr, line)
  } REPEAT

  IF tracing DO
    writef("inco:  Sending zero to outco*n")

  writef("*nNumber of lines written was %n*n", cowrite(channelptr, 0))

  endstream(instream)
}

AND outfn(args) BE
{ LET channelptr = args!0
  LET linecount = 0

  { LET line = coread(channelptr)
    UNLESS line BREAK
    IF tracing DO writef("outfn: Received a line*n")
    writes(line)
    linecount := linecount + 1
  } REPEAT

  IF tracing DO
    writef("outfn: Received zero, so sent count=%n back to inco*n",
            linecount)

  cowait(linecount)
}

// The following functions are a  implementation of Occum-style channels
// using coroutines.

// The first coroutine to request a transfer through a channel becomes
// suspended and the second causes the data to be transfers and then allows
// both coroutines to resume (in some order). The channel word is either
// zero or points to a suspended (read or write) cocoutine.

// The use of resumeco in coread is somewhat subtle!

AND coread(ptr) = VALOF
{ LET cptr = !ptr
  TEST cptr
  THEN { !ptr := 0         // Clear the channel word
         RESULTIS resumeco(cptr, currco)
       }
  ELSE { !ptr := currco    // Set channel word to this coroutine
         RESULTIS cowait() // Wait for value from cowrite
       }
}

AND cowrite(ptr, val) BE
{ LET cptr = !ptr
  TEST cptr
  THEN { !ptr := 0
         callco(cptr, val) // Send val to coread
       }
  ELSE { !ptr := currco
          callco(cowait(), val)
       }
}


#include <stdlib.h>	/* malloc(), realloc(), free() */
#include <stdio.h>	/* fopen(), fgetc(), fwrite(), printf() */

#include <libco.h>	/* co_create(), co_switch() */

void
fail(const char *message) {
	perror(message);
	exit(1);
}

/*
 * These are global variables of this process. All cothreads of this
 * process will share these global variables.
 */
cothread_t reader;
cothread_t printer;
struct {
	char	*buf;	/* Not a C string. No terminating '\0'. */
	size_t	len;	/* Length of line in buffer. */
	size_t	cap;	/* Maximum capacity of buffer. */
} line;
size_t count;		/* Number of lines printed. */

/*
 * The reader cothread reads every line of an input file, passes each
 * line to the printer cothread, and reports the number of lines.
 */
void
reader_entry(void)
{
	FILE *input;
	size_t newcap;
	int c, eof, eol;
	char *newbuf;

	input = fopen("input.txt", "r");
	if (input == NULL)
		fail("fopen");

	line.buf = malloc(line.cap = 4096);  /* New buffer. */
	if (line.buf == NULL)
		fail("malloc");
	line.len = 0;  /* Start with an empty line. */

	do {
		c = fgetc(input);  /* Read next character. */
		if (ferror(input))
			fail("fgetc");

		eof = (c == EOF);
		if (eof) {
			/*
			 * End of file is also end of line,
		`	 * unless the line would be empty.
			 */
			eol = (line.len > 0);
		} else {
			/* Append c to the buffer. */
			if (line.len == line.cap) {
				/* Need a bigger buffer! */
				newcap = line.cap * 2;
				newbuf = realloc(line.buf, newcap);
				if (newbuf == NULL)
					fail("realloc");
				line.buf = newbuf;
				line.cap = newcap;
			}
			line.buf[line.len++] = c;

			/* '\n' is end of line. */
			eol = (c == '\n');
		}

		if (eol) {
			/* Pass our complete line to the printer. */
			co_switch(printer);
			line.len = 0;  /* Destroy our line. */
		}
	} while (!eof);

	free(line.buf);
	line.buf = NULL;  /* Stops a loop in the printer. */

	printf("Printed %zu lines.\n", count);
	co_switch(printer);
}

/*
 * The printer cothread starts the reader cothread, prints every line
 * line from the reader cothread, and counts the number of lines.
 */
int
main()
{
	reader = co_create(4096, reader_entry);
	printer = co_active();
	count = 0;

	for (;;) {
		co_switch(reader);
		if (line.buf == NULL)
			break;

		/* Print this line. Count it. */
		fwrite(line.buf, 1, line.len, stdout);
		count++;
	}

	co_delete(reader);
	return 0;
}


using System;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.IO;

namespace SynchronousConcurrency
{
    class Program
    {
        static void Main(string[] args)
        {
            BlockingCollection<string> toWriterTask = new BlockingCollection<string>();
            BlockingCollection<int> fromWriterTask = new BlockingCollection<int>();
            Task writer = Task.Factory.StartNew(() => ConsoleWriter(toWriterTask, fromWriterTask));
            Task reader = Task.Factory.StartNew(() => FileReader(fromWriterTask, toWriterTask));
            Task.WaitAll(writer, reader);
        }
        static void ConsoleWriter(BlockingCollection<string> input, BlockingCollection<int> output)
        {
            int nLines = 0;
            string line;
            while ((line = input.Take()) != null)
            {
                Console.WriteLine(line);
                ++nLines;
            }
            output.Add(nLines);
        }
        static void FileReader(BlockingCollection<int> input, BlockingCollection<string> output)
        {
            StreamReader file = new StreamReader("input.txt"); // TODO: check exceptions
            string line;
            while ((line = file.ReadLine()) != null)
            {
                output.Add(line);

            }
            output.Add(null); // EOF
            Console.WriteLine("line count: " + input.Take());
        }
    }
}


#include <future>
#include <iostream>
#include <fstream>
#include <mutex>
#include <queue>
#include <string>
#include <thread>

struct lock_queue
{
    std::queue<std::string> q;
    std::mutex mutex;
};

void reader(std::string filename, std::future<size_t> lines, lock_queue& out)
{
    std::string line;
    std::ifstream in(filename);
    while(std::getline(in, line)) {
        line += '\n';
        std::lock_guard<std::mutex> lock(out.mutex);
        out.q.push(line);
    } {
        std::lock_guard<std::mutex> lock(out.mutex);
        out.q.push("");
    }
    lines.wait();
    std::cout << "\nPrinted " << lines.get() << " lines\n";
}

void printer(std::promise<size_t> lines, lock_queue& in)
{
    std::string s;
    size_t line_n = 0;
    bool print = false;
    while(true) {
        {
            std::lock_guard<std::mutex> lock(in.mutex);
            if(( print = not in.q.empty() )) { //Assignment intended
                s = in.q.front();
                in.q.pop();
            }
        }
        if(print) {
            if(s == "") break;
            std::cout << s;
            ++line_n;
            print = false;
        }
    }
    lines.set_value(line_n);
}

int main()
{
    lock_queue queue;
    std::promise<size_t> promise;
    std::thread t1(reader, "input.txt", promise.get_future(), std::ref(queue));
    std::thread t2(printer, std::move(promise), std::ref(queue));
    t1.join(); t2.join();
}


(use '[clojure.java.io :as io])

(def writer (agent 0))

(defn write-line [state line]
  (println line)
  (inc state))


(defvar *self*)

(defclass queue ()
  ((condition :initform (make-condition-variable)
              :reader condition-of)
   (mailbox :initform '()
            :accessor mailbox-of)
   (lock :initform (make-lock)
         :reader lock-of)))

(defun message (recipient name &rest message)
  (with-lock-held ((lock-of recipient))
    ;; it would have been better to implement tail-consing or a LIFO
    (setf (mailbox-of recipient)
          (nconc (mailbox-of recipient)
                 (list (list* name message))))
    (condition-notify (condition-of recipient)))
  message)

(defun mklist (x)
  (if (listp x)
      x
      (list x)))

(defun slurp-message ()
  (with-lock-held ((lock-of *self*))
    (if (not (endp (mailbox-of *self*)))
        (pop (mailbox-of *self*))
        (progn (condition-wait (condition-of *self*)
                               (lock-of *self*))
               (assert (not (endp (mailbox-of *self*))))
               (pop (mailbox-of *self*))))))

(defmacro receive-message (&body cases)
  (let ((msg-name (gensym "MESSAGE"))
        (block-name (gensym "BLOCK")))
    `(let ((,msg-name (slurp-message)))
       (block ,block-name
         ,@(loop for i in cases
                 for ((name . case) . body) = (cons (mklist (car i))
                                                    (cdr i))
                 when (typep i '(or (cons (eql quote)
                                          t)
                                    (cons (cons (eql quote) t)
                                          t)))
                   do (warn "~S is a quoted form" i)
                 collect `(when ,(if (null name)
                                     't
                                     `(eql ',name (car ,msg-name)))
                            (destructuring-bind ,case
                                (cdr ,msg-name)
                              (return-from ,block-name
                                (progn ,@body)))))
         (error "Unknown message: ~S" ,msg-name)))))

(defmacro receive-one-message (message &body body)
  `(receive-message (,message . ,body)))

(defun queue () (make-instance 'queue))


File.write("input.txt", "a\nb\nc")

lines = Channel(String).new

spawn do
  File.each_line("input.txt") do |line|
    lines.send(line)
  end
  lines.close
end

while line = lines.receive?
  puts line
end

File.delete("input.txt")


import std.algorithm, std.concurrency, std.stdio;

void main() {
    auto printer = spawn(&printTask, thisTid);
    auto f = File("input.txt","r");
    foreach (string line; lines(f))
        send(printer, line);
    send(printer, true);    //EOF
    auto n = receiveOnly!(int)();
    stdout.writefln("\n%d lines printed.", n);
}

void printTask(Tid reader) {
    int n = 0;
    for (bool eof = false; !eof;)
        receive(
            (string line) {stdout.write(line); n++;},
            (bool) {send(reader, n); eof = true;}
        );
}


program Project2;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes, Windows;

type
  EThreadStackFinalized = class(Exception);

  PLine = ^TLine;
  TLine = record
    Text: string;
  end;

  TThreadQueue = class
  private
    FFinalized: Boolean;
    FQueue: THandle;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Finalize;
    procedure Push(Data: Pointer);
    function Pop(var Data: Pointer): Boolean;
    property Finalized: Boolean read FFinalized;
  end;

  TPrintThread = class(TThread)
  private
    FCount: Integer;
    FTreminateEvent: THandle;
    FDoneEvent: THandle;
    FQueue: TThreadQueue;
  public
    constructor Create(aTreminateEvent, aDoneEvent: THandle; aQueue: TThreadQueue);
    procedure Execute; override;

    property Count: Integer read FCount;
  end;

{ TThreadQueue }

constructor TThreadQueue.Create;
begin
  FQueue := CreateIOCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0);
  FFinalized := False;
end;

destructor TThreadQueue.Destroy;
begin
  if FQueue <> 0 then
    CloseHandle(FQueue);
  inherited;
end;

procedure TThreadQueue.Finalize;
begin
  PostQueuedCompletionStatus(FQueue, 0, 0, Pointer($FFFFFFFF));
  FFinalized := True;
end;

function TThreadQueue.Pop(var Data: Pointer): Boolean;
var
  A: Cardinal;
  OL: POverLapped;
begin
  Result := True;
  if not FFinalized then
    GetQueuedCompletionStatus(FQueue, A, Cardinal(Data), OL, INFINITE);

  if FFinalized or (OL = Pointer($FFFFFFFF)) then begin
    Data := nil;
    Result := False;
    Finalize;
  end;
end;

procedure TThreadQueue.Push(Data: Pointer);
begin
  if FFinalized then
    raise EThreadStackFinalized.Create('Stack is finalized');

  PostQueuedCompletionStatus(FQueue, 0, Cardinal(Data), nil);
end;

{ TPrintThread }

constructor TPrintThread.Create(aTreminateEvent, aDoneEvent: THandle; aQueue: TThreadQueue);
begin
  inherited Create(True);
  FCount := 0;
  FreeOnTerminate := True;
  FTreminateEvent := aTreminateEvent;
  FDoneEvent := aDoneEvent;
  FQueue := aQueue;
end;

procedure TPrintThread.Execute;
var
  data: Pointer;
  line: PLine;
begin
  repeat
    if FQueue.Pop(data) then begin
      line := data;
      try
        Writeln(line^.Text);
        if line^.Text = #0 then
          SetEvent(FDoneEvent);
        Inc(FCount);
      finally
        Dispose(line);
      end;
    end;

  until False;
  WaitForSingleObject(FTreminateEvent, INFINITE);
end;

var
  PrintThread: TPrintThread;
  Queue: TThreadQueue;
  lines: TStrings;
  i: Integer;
  line: PLine;
  TreminateEvent, DoneEvent: THandle;
begin
  Queue := TThreadQueue.Create;
  try
    TreminateEvent := CreateEvent(nil, False, False, 'TERMINATE_EVENT');
    DoneEvent := CreateEvent(nil, False, False, 'DONE_EVENT');
    try
      PrintThread := TPrintThread.Create(TreminateEvent, DoneEvent, Queue);
      PrintThread.Start;
      lines := TStringList.Create;
      try
        lines.LoadFromFile('input.txt');
        for i := 0 to lines.Count - 1 do begin
          New(line);
          line^.Text := lines[i];
          Queue.Push(line);
        end;

        New(line);
        line^.Text := #0;
        Queue.Push(line);

        WaitForSingleObject(DoneEvent, INFINITE);

        New(line);
        line^.Text := IntToStr(PrintThread.Count);
        Queue.Push(line);

        SetEvent(TreminateEvent);
      finally
        lines.Free;
      end;
    finally
      CloseHandle(TreminateEvent);
      CloseHandle(DoneEvent)
    end;

    Readln;
  finally
    Queue.Free;
  end;
end.


def printer := {
    var count := 0
    def printer {
        to run(item) {
            count += 1
            println(item)
        }
        to getCount() {
            return count
        }
    }
}

def sender(lines) {
    switch (lines) {
        match [] {
            when (def count := printer <- getCount()) -> {
                println(`$count lines were printed.`)
            }
        }
        match [line] + rest {
            when (printer <- run(line)) -> {
                sender(rest)
            }
        }
    }
}

# Stream IO in E is not finished yet, so this example just uses a list.
sender(<file:input.txt>.getText().split("\n"))


(require 'sequences)
(require 'tasks)

;; inter-tasks message : (op-code . data)
(define (is-message? op message)
	(and message (equal? op (first message))))

;; reader task
(define (reader infile )
	(wait S)
	(define message (semaphore-pop S))
	(when (is-message? 'count message ) (writeln 'reader-> message) (task-stop-all))

	(if (first infile) ;; not EOF
	(set! message (cons 'write (next infile)))
	(set! message (list 'reader-count-please)))

	(semaphore-push S message)
	(signal S)
	infile)

(define (writer count)
	(wait S)
	(define message (semaphore-pop S))
	(when  (is-message? 'write message )
			(writeln (rest message))
			(set! count (1+ count))
			(set! message (cons 'ack count)))

	(when  (is-message? 'reader-count-please message )
		 (set! message (cons 'count count)))
	(semaphore-push S message)
	(signal S)
	count)


defmodule RC do
  def start do
     my_pid = self
     pid = spawn( fn -> reader(my_pid, 0) end )
     File.open( "input.txt", [:read], fn io ->
       process( IO.gets(io, ""), io, pid )
     end )
  end

  defp process( :eof, _io, pid ) do
    send( pid, :count )
    receive do
      i -> IO.puts "Count:#{i}"
    end
  end
  defp process( any, io, pid ) do
    send( pid, any )
    process( IO.gets(io, ""), io, pid )
  end

  defp reader( pid, c ) do
    receive do
      :count -> send( pid, c )
      any ->
        IO.write any
        reader( pid, c+1 )
    end
  end
end

RC.start


-module(cc).

-export([start/0]).

start() ->
   My_pid = erlang:self(),
   Pid = erlang:spawn( fun() -> reader(My_pid, 0) end ),
   {ok, IO } = file:open( "input.txt", [read] ),
   process( io:get_line(IO, ""), IO, Pid ),
   file:close( IO ).

process( eof, _IO, Pid ) ->
   Pid ! count,
   receive
       I -> io:fwrite("Count:~p~n", [I])
   end;
process( Any, IO, Pid ) ->
   Pid ! Any,
   process( io:get_line(IO, ""), IO, Pid ).

reader(Pid, C) ->
   receive
       count -> Pid ! C;
       Any ->
           io:fwrite("~s", [Any]),
           reader(Pid, C+1)
   end.


sequence lines
sequence count
lines = {}
count = {}

procedure read(integer fn)
    object line
    while 1 do
        line = gets(fn)
        if atom(line) then
            exit
        else
            lines = append(lines, line)
            task_yield()
        end if
    end while

    lines = append(lines,0)
    while length(count) = 0 do
        task_yield()
    end while

    printf(1,"Count: %d\n",count[1])
end procedure

procedure write(integer fn)
    integer n
    object line
    n = 0
    while 1 do
        while length(lines) = 0 do
            task_yield()
        end while

        line = lines[1]
        lines = lines[2..$]
        if atom(line) then
            exit
        else
            puts(fn,line)
            n += 1
        end if
    end while
    count = append(count,n)
end procedure

integer fn
atom reader, writer
constant stdout = 1
fn = open("input.txt","r")
reader = task_create(routine_id("read"),{fn})
writer = task_create(routine_id("write"),{stdout})
task_schedule(writer,1)
task_schedule(reader,1)

while length(task_list()) > 1 do
    task_yield()
end while


open System.IO

type Msg =
    | PrintLine of string
    | GetCount of AsyncReplyChannel<int>

let printer =
    MailboxProcessor.Start(fun inbox ->
        let rec loop count =
            async {
                let! msg = inbox.Receive()
                match msg with
                | PrintLine(s) ->
                    printfn "%s" s
                    return! loop (count + 1)
                | GetCount(reply) ->
                    reply.Reply(count)
                    return! loop count
            }
        loop 0
    )

let reader (printAgent:MailboxProcessor<Msg>) file =
    File.ReadLines(file)
    |> Seq.iter (fun line -> PrintLine line |> printAgent.Post)
    printAgent.PostAndReply(fun reply -> GetCount(reply))
    |> printfn "Lines written: %i"

reader printer @"c:\temp\input.txt"


\
\ co.fs		Coroutines by continuations.
\
\ * Circular Queue. Capacity is power of 2.
\
	VARIABLE HEAD VARIABLE TAIL
	128 CELLS CONSTANT CQ#
\ * align by queue capacity
	HERE DUP
		CQ# 1- INVERT AND CQ# +
	SWAP - ALLOT
\
	HERE CQ# ALLOT CONSTANT START
\
: ADJUST   (  -- )   [ CQ# 1- ]L AND START + ;
: PUT      ( n-- )   TAIL @ TUCK ! CELL+ ADJUST TAIL ! ;
: TAKE 	   ( --n )   HEAD @ DUP @ SWAP CELL+ ADJUST HEAD ! ;
: 0CQ	   ( --  )   START DUP HEAD ! TAIL ! ; 0CQ
: NOEMPTY? ( --f )   HEAD @ TAIL @ <> ;
: ;CO      ( --  )   TAKE >R ;
\
\ * COROUTINES LEXEME
\
: CO:  ( -- )   R>  PUT ;	  \ Register continuation as coroutine. Exit.
: CO   ( -- )   R>  PUT TAKE >R ; \ Co-route.
: GO   ( -- )   BEGIN NOEMPTY? WHILE ;CO REPEAT ; \ :-)
\
\ * CHANNELS LEXEME
\
: CHAN?  ( a--f )   [email protected] XOR ;


package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    lines := make(chan string)
    count := make(chan int)
    go func() {
        c := 0
        for l := range lines {
            fmt.Println(l)
            c++
        }
        count <- c
    }()

    f, err := os.Open("input.txt")
    if err != nil {
        log.Fatal(err)
    }
    for s := bufio.NewScanner(f); s.Scan(); {
        lines <- s.Text()
    }
    f.Close()
    close(lines)
    fmt.Println("Number of lines:", <-count)
}


import Control.Concurrent
import Control.Concurrent.MVar

main =
    do lineVar <- newEmptyMVar
       countVar <- newEmptyMVar

       let takeLine  = takeMVar lineVar
           putLine   = putMVar lineVar . Just
           putEOF    = putMVar lineVar Nothing
           takeCount = takeMVar countVar
           putCount  = putMVar countVar

       forkIO $ writer takeLine putCount
       reader putLine putEOF takeCount


procedure main(A)
    fName := A[1]|"index.txt"
    p := thread produce(fName)
    c := thread consume(p)
    every wait(p | c)
end

procedure produce(fName)
    every !open(fName)@>>    # drop messages in p's outbox (blocking whenever box is full)
    @>>                      # Signal consumer that p is done
    write("count is ",<<@)   # block until message in p's inbox
end

procedure consume(p)
    i := 0
    while write(\<<@p) do (i+:=1)  # loop until empty message in p's outbox
                                   #    (blocking until each message arrives)
    i@>>p                          # put row count into p's inbox
end


input=: 1 :0
  nlines=: 0
  u;._2@fread 'input.txt'
  smoutput nlines
)

output=: 3 :0
  nlines=: nlines+1
  smoutput y
)


import java.io.BufferedReader;
import java.io.FileReader;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class SynchronousConcurrency
{
  public static void main(String[] args) throws Exception
  {
    final AtomicLong lineCount = new AtomicLong(0);
    final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
    final String EOF = new String();

    final Thread writerThread = new Thread(new Runnable() {
        public void run()
        {
          long linesWrote = 0;
          while (true)
          {
            try
            {
              String line = queue.take();
              // Reference equality
              if (line == EOF)
                break;
              System.out.println(line);
              linesWrote++;
            }
            catch (InterruptedException ie)
            {  }
          }
          lineCount.set(linesWrote);
        }
      }
    );
    writerThread.start();

    // No need to start a third thread for the reader, just use this thread
    BufferedReader br = new BufferedReader(new FileReader("input.txt"));
    String line;
    while ((line = br.readLine()) != null)
      queue.put(line);
    br.close();
    queue.put(EOF);
    writerThread.join();
    // AtomicLong is not needed here due to memory barrier created by thread join, but still need a mutable long since lineCount must be final to access it from an anonymous class
    System.out.println("Line count: " + lineCount.get());
    return;
  }
}


function inputlines(txtfile, iochannel)
    for line in readlines(txtfile)
        Base.put!(iochannel, line)
    end
    Base.put!(iochannel, nothing)
    println("The other task printed $(take!(iochannel)) lines.")
end

function outputlines(iochannel)
    totallines = 0
    while (line = Base.take!(iochannel)) != nothing
        totallines += 1
        println(line)
    end
    Base.put!(iochannel, totallines)
end

c = Channel(0)
@async inputlines("filename.txt", c)
outputlines(c)


import java.util.concurrent.SynchronousQueue
import kotlin.concurrent.thread
import java.io.File

const val EOT = "\u0004"  // end of transmission

fun main(args: Array<String>) {
    val queue = SynchronousQueue<String>()

    val work = thread {
        var count = 0

        while (true) {
             val line = queue.take()
             if (line == EOT) {
                queue.put(count.toString())
                break
             }
             println(line)
             count++
        }
    }

    File("input.txt").forEachLine { line -> queue.put(line) }
    queue.put(EOT)
    work.join()

    val count = queue.take().toInt()
    println("\nNumber of lines printed = $count")
}


:- object(team).

    :- threaded.

    :- public(start/0).
    start :-
        threaded((
            reader,
            writer(0)
        )).

    reader :-
        open('input.txt', read, Stream),
        repeat,
            read_term(Stream, Term, []),
            threaded_notify(term(Term)),
        Term == end_of_file,
        !,
        close(Stream),
        threaded_wait(lines(Lines)),
        write('Number of lines: '), write(Lines), nl.

    writer(N0) :-
        threaded_wait(term(Term)),
        (   Term == end_of_file ->
            threaded_notify(lines(N0))
        ;   N is N0 + 1,
            write(Term), nl,
            writer(N)
        ).

:- end_object.


function ReadFile()
    local fp = io.open( "input.txt" )
    assert( fp ~= nil )

    for line in fp:lines() do
	coroutine.yield( line )
    end

    fp:close()
end

co = coroutine.create( ReadFile )

while true do
    local status, val = coroutine.resume( co )
    if coroutine.status( co ) == "dead" then break end
    print( val )
end


:- module synchronous_concurrency.
:- interface.
:- import_module io.

:- pred main(io::di, io::uo) is cc_multi.

:- implementation.
:- import_module int, list, string, thread, thread.channel, thread.mvar.

:- type line_or_stop
    --->    line(string)
    ;       stop.

main(!IO) :-
    io.open_input("input.txt", Res, !IO),
    (
        Res = ok(Input),
        channel.init(Channel, !IO),
        mvar.init(MVar, !IO),
        thread.spawn(writer(Channel, MVar, 0), !IO),
        reader(Input, Channel, MVar, !IO)
    ;
        Res = error(Err),
        io.format("Error opening file: %s\n", [s(io.error_message(Err))], !IO)
    ).

:- pred reader(io.text_input_stream::in, channel(line_or_stop)::in, mvar(int)::in,
    io::di, io::uo) is det.

reader(Input, Channel, MVar, !IO) :-
    io.read_line_as_string(Input, Res, !IO),
    (
        Res = ok(Line),
        channel.put(Channel, line(Line), !IO),
        reader(Input, Channel, MVar, !IO)
    ;
        Res = eof,
        channel.put(Channel, stop, !IO),
        mvar.take(MVar, Count, !IO),
        io.format("%d lines printed.\n", [i(Count)], !IO)
    ;
        Res = error(Err),
        channel.put(Channel, stop, !IO),
        io.format("Error reading file: %s\n", [s(io.error_message(Err))], !IO)
    ).

:- pred writer(channel(line_or_stop)::in, mvar(int)::in, int::in,
    io::di, io::uo) is cc_multi.

writer(Channel, MVar, Count, !IO) :-
    channel.take(Channel, LineOrStop, !IO),
    (
        LineOrStop = line(Line),
        io.write_string(Line, !IO),
        writer(Channel, MVar, Count + 1, !IO)
    ;
        LineOrStop = stop,
        mvar.put(MVar, Count, !IO)
    ).


var msgs: Channel[string]
var count: Channel[int]

const FILE = "input.txt"

proc read() {.thread.} =
  for line in FILE.lines:
    msgs.send(line)
  msgs.send("")
  echo count.recv()
  count.close()

proc print() {.thread.} =
  var n = 0
  while true:
    var msg = msgs.recv()
    if msg.len == 0:
      break
    echo msg
    n += 1
  msgs.close()
  count.send(n)

var reader_thread = Thread[void]()
var printer_thread = Thread[void]()

msgs.open()
count.open()
createThread(reader_thread, read)
createThread(printer_thread, print)
joinThreads(reader_thread, printer_thread)


import: parallel

: printing(chPrint, chCount)
  0 while( chPrint receive dup notNull ) [ println 1+ ] drop
  chCount send drop ;

: concurrentPrint(aFileName)
| chPrint chCount line |
   Channel new ->chPrint
   Channel new ->chCount

   #[ printing(chPrint, chCount) ] &

   aFileName File new forEach: line [ chPrint send(line) drop ]
   chPrint close
   chCount receive "Number of lines printed : " print println ;


(import (owl parse))

(coroutine 'reader (lambda ()
   ; lazy line-by-line file reader
   (define (not-a-newline x) (not (eq? x #\newline)))
   (define parser (let-parse*
                        ((line (greedy* (byte-if not-a-newline)))
                         (newline (imm #\newline)))
                     (bytes->string line)))
   (define file (file->bytestream "input.txt"))

   (let loop ((in (try-parse parser file #false)))
      (cond
         ((not in) ; file is ended
            (define envelope (wait-mail)) ; wait for a request
            (mail (ref envelope 1) #eof)) ; send an end-of-file to caller
         ((pair? in) ; new line is read
            (define envelope (wait-mail)) ; wait for a request
            (mail (ref envelope 1) (car in)) ; send a line to caller
            (loop (try-parse parser (cdr in) #false)))
         (else ; just a lazy read, let's repeat
            (loop (force in)))))

   (print "total lines read: " (await (mail 'writer #t)))
))

(coroutine 'writer (lambda ()
   (let loop ((n 0))
      (define line (await (mail 'reader #t)))

      (if (eof? line)
      then
         (define envelope (wait-mail)) ; wait for a request
         (mail (ref envelope 1) n) ; send a lines count to caller
      else
         (print "read line: " line)
         (loop (+ n 1))))))