PROCEDURE ReadName (VAR str : ARRAY OF CHAR);

VAR     n               : CARDINAL;
        ch, endch       : CHAR;

BEGIN
   REPEAT
      InOut.Read (ch);
      Exhausted := InOut.EOF ();
      IF  Exhausted  THEN  RETURN  END
   UNTIL  ch > ' ';             (* Eliminate whitespace         *)
   IF  ch = '['  THEN  endch := ']'  ELSE  endch := ch  END;
   n := 0;
   REPEAT
      InOut.Read (ch);
      Exhausted := InOut.EOF ();
      IF  Exhausted  THEN  RETURN  END;
      IF  n <= HIGH (str)  THEN  str [n] := ch  ELSE  ch := endch  END;
      INC (n)
   UNTIL ch = endch;
   IF  n <= HIGH (str)  THEN  str [n-1] := 0C  END;
   lastCh := ch
END ReadName;


MODULE Output EXPORTS Main;

IMPORT Rd, Wr, Stdio;

VAR buf: TEXT;

<*FATAL ANY*>

BEGIN
  WHILE NOT Rd.EOF(Stdio.stdin) DO
    buf := Rd.GetLine(Stdio.stdin);
    Wr.PutText(Stdio.stdout, buf);
  END;
END Output.


/* NetRexx */
options replace format comments java crossref symbols nobinary

-- Read from default input stream (console) until end of data
lines = ''
lines[0] = 0
lineNo = 0

loop label ioloop forever
  inLine = ask
  if inLine =  null  then leave ioloop -- stop on EOF (Try Ctrl-D on UNIX-like systems or Ctrl-Z on Windows)
  lineNo = lineNo + 1
  lines[0] = lineNo
  lines[lineNo] = inLine
  end ioloop

loop l_ = 1 to lines[0]
  say l_.right(4)':' lines[l_]
  end l_

return


var line = ""
while stdin.readLine(line):
  echo line


MODULE InputLoop;
IMPORT
  StdChannels,
  Channel;
VAR
  reader: Channel.Reader;
  writer: Channel.Writer;
  c: CHAR;
BEGIN
  reader := StdChannels.stdin.NewReader();
  writer := StdChannels.stdout.NewWriter();

  reader.ReadByte(c);
  WHILE reader.res = Channel.done DO
    writer.WriteByte(c);
    reader.ReadByte(c)
  END
END InputLoop.


use IO;

bundle Default {
  class Test {
    function : Main(args : System.String[]) ~ Nil {
      f := FileReader->New("in.txt");
      if(f->IsOpen()) {
        string := f->ReadString();
        while(string->Size() > 0) {
          string->PrintLine();
          string := f->ReadString();
        };
        f->Close();
      };
    }
  }
}


let rec read_lines ic =
  try let line = input_line ic in
    line :: read_lines ic
  with End_of_file ->
    []


: readFile(filename)   File new(filename) apply(#println) ;


%% Returns a list of lines.
%% Text: an instance of Open.text (a mixin class)
fun {ReadAll Text}
   case {Text getS($)} of false then nil
   [] Line then Line|{ReadAll Text}
   end
end


{ for stdio }

var

 s : string ;

begin

  repeat

    readln(s);

  until s = "" ;

{ for a file }

var

 f : text ;
 s : string ;

begin

  assignfile(f,'foo');
  reset(f);

  while not eof(f) do
    readln(f,s);

  closefile(f);

end;


open FH, "< $filename" or die "can't open file: $!";
while (my $line = <FH>) {
    chomp $line; # removes trailing newline
    # process $line
}
close FH or die "can't close file: $!";


without js -- (file i/o)
procedure process_line_by_line(integer fn)
    object line
    while 1 do
        line = gets(fn)
        if atom(line) then
            exit
        end if
        -- process the line
    end while
end procedure


$fh = fopen($filename, 'r');
if ($fh) {
    while (!feof($fh)) {
        $line = rtrim(fgets($fh)); # removes trailing newline
        # process $line
    }
    fclose($fh);
}


trace(5 / 0); // outputs "Infinity"
trace(isFinite(5 / 0)); // outputs "false"


with Ada.Text_IO; use Ada.Text_IO;

procedure Infinities is
   function Sup return Float is -- Only for predefined types
      Result : Float := Float'Last;
   begin
      if not Float'Machine_Overflows then
         Result := Float'Succ (Result);
      end if;
      return Result;
   end Sup;

   function Inf return Float is -- Only for predefined types
      Result : Float := Float'First;
   begin
      if not Float'Machine_Overflows then
         Result := Float'Pred (Result);
      end if;
      return Result;
   end Inf;
begin
   Put_Line ("Supremum" & Float'Image (Sup));
   Put_Line ("Infimum " & Float'Image (Inf));
end Infinities;


printf(($"max int: "gl$,max int));
printf(($"long max int: "gl$,long max int));
printf(($"long long max int: "gl$,long long max int));
printf(($"max real: "gl$,max real));
printf(($"long max real: "gl$,long max real));
printf(($"long long max real: "gl$,long long max real));
printf(($"error char: "gl$,error char))


main =>
  Reader = open("file.txt"),
  while(not at_end_of_stream(Reader))
    L = read_line(Reader),
    println(L)
  end,
  close(Reader).


(in "file.txt"
   (make
      (until (eof)
         (link (line)) ) ) )


declare line character (200) varying;

open file (in) title ('/TEXT.DAT,type(text),recsize(200)' );
on endfile (in) stop;

do forever;
   get file(in) edit (line) (L);
   put skip list (line);
end;


Get-Content c:\file.txt |
    ForEach-Object {
        $_
    }


If OpenConsole()
  ; file based line wise
  If ReadFile(0, "Text.txt")
    While Eof(0) = 0
      Debug ReadString(0)      ; each line until eof
    Wend
    CloseFile(0)
  EndIf

  ; file based byte wise
  If ReadFile(1, "Text.bin")
    While Eof(1) = 0
      Debug ReadByte(1)      ; each byte until eof
    Wend
    CloseFile(1)
  EndIf
EndIf


use std
printf "%f\n" atof "infinity" (: this prints "inf" :)
#extern :atof<text>: -> real


  BEGIN {
    k=1;
    while (2^(k-1) < 2^k) k++;
    INF = 2^k;
    print INF;
  }


onerror TratoError
infinity = 1e300*1e300
end

TratoError:
if lasterror = 29 then print lasterrormessage
return


      *FLOAT 64
      PRINT FNinfinity
      END

      DEF FNinfinity
      LOCAL supported%, maxpos, prev, inct
      supported% = TRUE
      ON ERROR LOCAL supported% = FALSE
      IF supported% THEN = 1/0
      RESTORE ERROR
      inct = 1E10
      REPEAT
        prev = maxpos
        inct *= 2
        ON ERROR LOCAL inct /= 2
        maxpos += inct
        RESTORE ERROR
      UNTIL maxpos = prev
      = maxpos


while(True):
      x = input("What is your age? ")
      print(x)


#lang racket
(copy-port (current-input-port) (current-output-port))


rebol [
	Title: "Basic Input Loop"
	URL: http://rosettacode.org/wiki/Basic_input_loop
]

; Slurp the whole file in:
x: read %file.txt

; Bring the file in by lines:
x: read/lines %file.txt

; Read in first 10 lines:
x: read/lines/part %file.txt 10

; Read data a line at a time:
f: open/lines %file.txt
while [not tail? f][
	print f/1
	f: next f ; Advance to next line.
]
close f


   ∞ + 1
∞
   ∞ - 3
∞
   -∞
¯∞
   ∞ - ∞
NaN


#include <math.h>	/* HUGE_VAL */
#include <stdio.h>	/* printf() */

double inf(void) {
  return HUGE_VAL;
}

int main() {
  printf("%g\n", inf());
  return 0;
}


F rank(x)
   R BigInt(([1] [+] x).map(String).join(‘A’), radix' 11)

F unrank(n)
   V s = String(n, radix' 11)
   R s.split(‘A’).map(Int)[1..]

V l = [1, 2, 3, 10, 100, 987654321]
print(l)
V n = rank(l)
print(n)
l = unrank(n)
print(l)


do while stream(stdin, "State") <> "NOTREADY"
  call charout ,charin(stdin)
end


fp = fopen("C:\Ring\ReadMe.txt","r")

r = fgetc(fp)
while isstring(r)
      r = fgetc(fp)
      if r = char(10) see nl
      else see r ok
end
fclose(fp)


stream = $stdin
stream.each do |line|
  # process line
end


open "\testFile.txt" for input as #f
while not(eof(#f))
line input #f, a$
print a$
wend
close #f


 use std::io::{self, BufReader, Read, BufRead};
use std::fs::File;

fn main() {
    print_by_line(io::stdin())
        .expect("Could not read from stdin");

    File::open("/etc/fstab")
        .and_then(print_by_line)
        .expect("Could not read from file");
}

fn print_by_line<T: Read>(reader: T) -> io::Result<()> {
    let buffer = BufReader::new(reader);
    for line in buffer.lines() {
        println!("{}", line?)
    }
    Ok(())
}


using System;

class Program
{
    static double PositiveInfinity()
    {
        return double.PositiveInfinity;
    }

    static void Main()
    {
        Console.WriteLine(PositiveInfinity());
    }
}


#include <limits>

double inf()
{
  if (std::numeric_limits<double>::has_infinity)
    return std::numeric_limits<double>::infinity();
  else
    return std::numeric_limits<double>::max();
}


##Inf  ;; same as Double/POSITIVE_INFINITY
##-Inf ;; same as Double/NEGATIVE_INFINITY
(Double/isInfinite ##Inf) ;; true


> (apropos "MOST-POSITIVE" :cl)
MOST-POSITIVE-LONG-FLOAT, value: 1.7976931348623158D308
MOST-POSITIVE-SHORT-FLOAT, value: 3.4028172S38
MOST-POSITIVE-SINGLE-FLOAT, value: 3.4028235E38
MOST-POSITIVE-DOUBLE-FLOAT, value: 1.7976931348623158D308
MOST-POSITIVE-FIXNUM, value: 536870911

> (apropos "MOST-NEGATIVE" :cl)
MOST-NEGATIVE-SINGLE-FLOAT, value: -3.4028235E38
MOST-NEGATIVE-LONG-FLOAT, value: -1.7976931348623158D308
MOST-NEGATIVE-SHORT-FLOAT, value: -3.4028172S38
MOST-NEGATIVE-DOUBLE-FLOAT, value: -1.7976931348623158D308
MOST-NEGATIVE-FIXNUM, value: -536870912


rank: function [arr][
    if empty? arr -> return 0
    from.binary "1" ++ join.with:"0" map arr 'a -> repeat "1" a
]

unrank: function [rnk][
    if rnk=1 -> return [0]
    bn: as.binary rnk
    map split.by:"0" slice bn 1 dec size bn => size
]

l: [1, 2, 3, 5, 8]

print ["The initial list:" l]

r: rank l
print ["Ranked:" r]

u: unrank r
print ["Unranked:" u]


import std.stdio, std.algorithm, std.array, std.conv, std.bigint;

BigInt rank(T)(in T[] x) pure /*nothrow*/ @safe {
    return BigInt("0x" ~ x.map!text.join('F'));
}

BigInt[] unrank(BigInt n) pure /*nothrow @safe*/ {
    string s;
    while (n) {
        s = "0123456789ABCDEF"[n % 16] ~ s;
        n /= 16;
    }
    return s.split('F').map!BigInt.array;
}

void main() {
    immutable s = [1, 2, 3, 10, 100, 987654321];
    s.writeln;
    s.rank.writeln;
    s.rank.unrank.writeln;
}


type duple
    A as ulongint
    B as ulongint
end type

function two_to_one( A as ulongint, B as ulongint ) as ulongint   'converts two numbers into one
    dim as uinteger ret = A*A + B*B + 2*A*B - 3*A - B             'according to the table
    return 1 + ret/2                                              '    1  2  3  4  5
end function                                                      '    -------------
                                                                  ' 1| 1  3  6 10 15
function one_to_two( R as ulongint ) as duple                     ' 2| 2  5  9 14 20
    dim as uinteger t = int((-1+sqr(8*R-7))/2)                    ' 3| 4  8 13 19 26
    dim as duple ret                                              ' 4| 7 12 18 25 33
    ret.A = (t*t+3*t+4)/2-R
    t = int((-1+sqr(8*R-7))/2)                                    'and the inverse of this
    ret.B = R-t*(t+1)/2
    return ret
end function

function rank( N() as ulongint) as ulongint
    dim as uinteger ret, num = ubound(N)+1
    if num = 0 then return 0                                      'define a value of 0 for the empty list
    if num = 1 then return two_to_one( N(0), 1 )
    ret = two_to_one( N(0), N(1) )
    for i as uinteger = 2 to num-1                                'progressively encode the list by
        ret = two_to_one( ret, N(i) )                             'applying 2to1 on the result of the
    next i                                                        'previous calculation with the next list element
    return two_to_one(ret, num)                                   'store the length of the list as
end function                                                      'the final component

sub unrank( R as ulongint, N() as ulongint )
    dim as duple temp
    if R = 0 then                                                 'zero yields the empty list
        redim N(-1)
        return
    end if
    dim as ulongint num, Q(0 to 1)
    temp = one_to_two( R )
    num = temp.B                                                  'first get the length of the encoded list
    redim N(0 to num-1) as ulongint
    if num = 1 then                                               '(singleton handled as a special case)
        N(0)=temp.A
        return
    end if
    for i as integer = num-1 to 2 step -1                         'get back the list elements one by one
        temp = one_to_two( temp.A )                               'in the reverse order they were added
        N(i) = temp.B
    next i
    temp = one_to_two( temp.A )                                   'finally get the initial two list elements
    N(0) = temp.A
    N(1) = temp.B
end sub

sub show_list( L() as ulongint )
    dim as integer num = ubound(L)
    if num=-1 then
        print "[]"
        return
    end if
    print "[";
    for i as integer = 0 to num-1
        print str(L(i))+", ";
    next i
    print str(L(num))+"]"
end sub
'A few tests
dim as duple temp
redim as uinteger ex0(-1) 'empty list
dim as ulongint R = rank(ex0())
R = rank(ex0())
print R,
redim as ulongint X(0 to 1)
unrank R, X()
show_list(X())

dim as uinteger ex1(0 to 0) = {13}   'list with 1 element
R = rank(ex1())
print R,
unrank R, X()
show_list(X())

dim as uinteger ex2(0 to 1) = {19, 361}   'list with 2 elements
R = rank(ex2())
print R,
redim as ulongint X(0 to 1)
unrank R, X()
show_list(X())

dim as uinteger ex6(0 to 5) = {1,2,1,2,3,1}   'list with 6 elements
R = rank(ex6())
print R,
unrank R, X()
show_list(X())


  scala.io.Source.fromFile("input.txt").getLines().foreach {
    line => ... }


$ include "seed7_05.s7i";

const proc: main is func
  local
    var string: line is "";
  begin
    while hasNext(IN) do
      readln(line);
      writeln("LINE: " <& line);
    end while;
  end func;


var file = File(__FILE__)
file.open_r(\var fh, \var err) || die "#{file}: #{err}"

fh.each { |line|              # iterates the lines of the fh
    line.each_word { |word|   # iterates the words of the line
        say word
    }
}


(File newNamed: 'README') reader sessionDo: [| :input | input lines do: [| :line | inform: line]].


MODULE Infinity;
IMPORT StdLog;

PROCEDURE Do*;
VAR
	x: REAL;
BEGIN
	x := 1 / 0;
	StdLog.String("x:> ");StdLog.Real(x);StdLog.Ln
END Do;


auto inf() {
    return typeof(1.5).infinity;
}

void main() {}


  Infinity    =  1.0 / 0.0;
  NegInfinity = -1.0 / 0.0;


def infinityTask() {
    return Infinity # predefined variable holding positive infinity
}


package main

import (
    "fmt"
    "math/big"
)

func rank(l []uint) (r big.Int) {
    for _, n := range l {
        r.Lsh(&r, n+1)
        r.SetBit(&r, int(n), 1)
    }
    return
}

func unrank(n big.Int) (l []uint) {
    m := new(big.Int).Set(&n)
    for a := m.BitLen(); a > 0; {
        m.SetBit(m, a-1, 0)
        b := m.BitLen()
        l = append(l, uint(a-b-1))
        a = b
    }
    return
}

func main() {
    var b big.Int
    for i := 0; i <= 10; i++ {
        b.SetInt64(int64(i))
        u := unrank(b)
        r := rank(u)
        fmt.Println(i, u, &r)
    }
    b.SetString("12345678901234567890", 10)
    u := unrank(b)
    r := rank(u)
    fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r)
}


import Data.List

toBase :: Int -> Integer -> [Int]
toBase b = unfoldr f
  where
    f 0 = Nothing
    f n = let (q, r) = n `divMod` fromIntegral b in Just (fromIntegral r, q)

fromBase :: Int -> [Int] -> Integer
fromBase n lst = foldr (\x r -> fromIntegral n*r + fromIntegral x) 0 lst

------------------------------------------------------------

listToInt :: Int -> [Int] -> Integer
listToInt b lst = fromBase (b+1) $ concat seq
  where
    seq = [ let (q, r) = divMod n b
            in replicate q 0 ++ [r+1]
          | n <- lst ]

intToList :: Int -> Integer -> [Int]
intToList b lst = go 0 $ toBase (b+1) lst
  where
    go 0 [] = []
    go i (0:xs) = go (i+1) xs
    go i (x:xs) = (i*b + x - 1) : go 0 xs


|f|
f := FileStream open: 'afile.txt' mode: FileStream read.
[ f atEnd ] whileFalse: [ (f nextLine) displayNl ] .


var line;
while (line = getline()) != nil {
    print(line);
}


fun foldLines f init strm =
  case TextIO.inputLine strm of
    SOME line => foldLines f (f (line, init)) strm
  | NONE => init


set fh [open $filename]
while {[gets $fh line] != -1} {
    # process $line
}
close $fh


class
	APPLICATION
inherit
	ARGUMENTS
create
	make
feature {NONE} -- Initialization
	number:REAL_64
	make
			-- Run application.
		do
			number := 2^2000
			print(number)
			print("%N")
			print(number.is_positive_infinity)
			print("%N")
		end
end


PROGRAM INFINITY

EXCEPTION
    PRINT("INFINITY")
    ESCI%=TRUE
END EXCEPTION

BEGIN
    ESCI%=FALSE
    K=1
    WHILE 2^K>0 DO
       EXIT IF ESCI%
       K+=1
    END WHILE
END PROGRAM


constant infinity = 1E400

? infinity -- outputs "inf"


import java.math.BigInteger;
import static java.util.Arrays.stream;
import java.util.*;
import static java.util.stream.Collectors.*;

public class Test3 {
    static BigInteger rank(int[] x) {
        String s = stream(x).mapToObj(String::valueOf).collect(joining("F"));
        return new BigInteger(s, 16);
    }

    static List<BigInteger> unrank(BigInteger n) {
        BigInteger sixteen = BigInteger.valueOf(16);
        String s = "";
        while (!n.equals(BigInteger.ZERO)) {
            s = "0123456789ABCDEF".charAt(n.mod(sixteen).intValue()) + s;
            n = n.divide(sixteen);
        }
        return stream(s.split("F")).map(x -> new BigInteger(x)).collect(toList());
    }

    public static void main(String[] args) {
        int[] s = {1, 2, 3, 10, 100, 987654321};
        System.out.println(Arrays.toString(s));
        System.out.println(rank(s));
        System.out.println(unrank(rank(s)));
    }
}


using LinearAlgebra
LinearAlgebra.rank(x::Vector{<:Integer}) = parse(BigInt, "1a" * join(x, 'a'), base=11)
function unrank(n::Integer)
    s = ""
    while !iszero(n)
        ind = n % 11 + 1
        n ÷= 11
        s = "0123456789a"[ind:ind] * s
    end
    return parse.(Int, split(s, 'a'))[2:end]
end

v = [0, 1, 2, 3, 10, 100, 987654321]
n = rank(v)
v = unrank(n)
println("# v = $v\n -> n = $n\n -> v = $v")


$$ MODE TUSCRIPT
file="a.txt"
ERROR/STOP OPEN (file,READ,-std-)
ACCESS source: READ/RECORDS/UTF8 $file s,text
LOOP
    READ/NEXT/EXIT source
    PRINT text
ENDLOOP
ENDACCESS source


while read line ; do
  # examine or do something to the text in the "line" variable
  echo "$line"
done


yes 'A B C D ' | while read x ; do echo -$x- ; done


decl file f
f.open "filename.txt"
while (f.hasnext)
	out (in string f) endl console
end while


int main() {
        string? s;
        while((s = stdin.read_line()) != null) {
                stdout.printf("%s\n", s);
        }
        return 0;
}


class Main
{
  static Float getInfinity () { Float.posInf }
  public static Void main () { echo (getInfinity ()) }
}


: inf ( -- f ) 1e 0e f/ ;
inf f.    \ implementation specific. GNU Forth will output "inf"

: inf? ( f -- ? ) s" MAX-FLOAT" environment? drop f> ;
\ IEEE infinity is the only value for which this will return true

: has-inf ( -- ? ) ['] inf catch if false else inf? then ;


program to_f_the_ineffable
   use, intrinsic :: ieee_arithmetic
   integer :: i
   real dimension(2) :: y, x = (/ 30, ieee_value(y,ieee_positive_inf) /)

   do i = 1, 2
      if (ieee_support_datatype(x(i))) then
         if (ieee_is_finite(x(i))) then
            print *, 'x(',i,') is finite'
         else
            print *, 'x(',i,') is infinite'
         end if

      else
         print *, 'x(',i,') is not in an IEEE-supported format'
      end if
   end do
end program to_f_the_ineffable


' FB 1.05.0 Win64

#Include "crt/math.bi"
#Print Typeof(1.5) ' Prints DOUBLE at compile time

Dim d As Typeof(1.5) = INFINITY
Print d; " (String representation of Positive Infinity)"
Sleep


# Floating point infinity
inf := FLOAT_INT(1) / FLOAT_INT(0);

IS_FLOAT(inf);
#true;

# GAP has also a formal ''infinity'' value
infinity in Cyclotomics;
# true


// version 1.1.2

import java.math.BigInteger

/* Separates each integer in the list with an 'a' then encodes in base 11. Empty list mapped to '-1' */
fun rank(li: List<Int>) = when (li.size) {
    0    -> -BigInteger.ONE
    else ->  BigInteger(li.joinToString("a"), 11)
}

fun unrank(r: BigInteger) = when (r) {
    -BigInteger.ONE -> emptyList<Int>()
    else            -> r.toString(11).split('a').map { if (it != "") it.toInt() else 0 }
}

/* Each integer n in the list mapped to '1' plus n '0's. Empty list mapped to '0' */
fun rank2(li:List<Int>): BigInteger {
    if (li.isEmpty()) return BigInteger.ZERO
    val sb = StringBuilder()
    for (i in li) sb.append("1" + "0".repeat(i))
    return BigInteger(sb.toString(), 2)
}

fun unrank2(r: BigInteger) = when (r) {
    BigInteger.ZERO -> emptyList<Int>()
    else            -> r.toString(2).drop(1).split('1').map { it.length }
}

fun main(args: Array<String>) {
    var li: List<Int>
    var r: BigInteger
    li = listOf(0, 1, 2, 3, 10, 100, 987654321)
    println("Before ranking   : $li")
    r = rank(li)
    println("Rank = $r")
    li = unrank(r)
    println("After unranking  : $li")

    println("\nAlternative approach (not suitable for large numbers)...\n")
    li = li.dropLast(1)
    println("Before ranking   : $li")
    r = rank2(li)
    println("Rank = $r")
    li = unrank2(r)
    println("After unranking  : $li")

    println()
    for (i in 0..10) {
        val bi = BigInteger.valueOf(i.toLong())
        li = unrank2(bi)
        println("${"%2d".format(i)} -> ${li.toString().padEnd(9)} -> ${rank2(li)}")
    }
}


ClearAll[Rank,Unrank]
Rank[x_List]:=FromDigits[Catenate[Riffle[IntegerDigits/@x,{{15}},{1,-1,2}]],16]
Unrank[n_Integer]:=FromDigits/@SequenceSplit[IntegerDigits[n,16],{15}]
Rank[{0,1,2,3,10,100,987654321,0}]
Unrank[%]
[email protected]*[email protected]*[email protected]*List /@ Range[0, 20]


import strformat, strutils
import bignum

func rank(list: openArray[uint]): Int =
  result = newInt(0)
  for n in list:
    result = result shl (n + 1)
    result = result.setBit(n)

func unrank(n: Int): seq[uint] =
  var m = n.clone
  var a = if m.isZero: 0u else: m.bitLen.uint
  while a > 0:
    m = m.clearBit(a - 1)
    let b = if m.isZero: 0u else: m.bitLen.uint
    result.add(a - b - 1)
    a = b

when isMainModule:

  var b: Int
  for i in 0..10:
    b = newInt(i)
    let u = b.unrank()
    let r = u.rank()
    echo &"{i:2d} {u:>9s} {r:>2s}"

  b = newInt("12345678901234567890")
  let u = b.unrank()
  let r = u.rank()
  echo &"\n{b}\n{u}\n{r}"


Public Sub test()
    Dim filesystem As Object, stream As Object, line As String
    Set filesystem = CreateObject("Scripting.FileSystemObject")
    Set stream = filesystem.OpenTextFile("D:\test.txt")
    Do While stream.AtEndOfStream <> True
        line = stream.ReadLine
        Debug.Print line
    Loop
    stream.Close
End Sub


filepath = "SPECIFY PATH TO TEXT FILE HERE"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFSO.OpenTextFile(filepath,1,False,0)

Do Until objInFile.AtEndOfStream
	line = objInFile.ReadLine
	WScript.StdOut.WriteLine line
Loop

objInFile.Close
Set objFSO = Nothing


Sub Consume(ByVal stream As IO.StreamReader)
    Dim line = stream.ReadLine
    Do Until line Is Nothing
        Console.WriteLine(line)
        line = stream.ReadLine
    Loop
End Sub


import "io" for File

File.open("input.txt") { |file|
    var offset = 0
    var line = ""
    while(true) {
        var b = file.readBytes(1, offset)
        offset = offset + 1
        if (b == "\n") {
            // process 'line'
            line = "" // reset line variable
        } else if (b == "\r") { // Windows
            // wait for following "\n"
        } else if (b == "") { // end of stream
            return
        } else {
            line = line + b
        }
    }
}


package main

import (
    "fmt"
    "math"
)

// function called for by task
func posInf() float64 {
    return math.Inf(1) // argument specifies positive infinity
}

func main() {
    x := 1.5 // type of x determined by literal
    // that this compiles demonstrates that PosInf returns same type as x,
    // the type specified by the task.
    x = posInf()                     // test function
    fmt.Println(x, math.IsInf(x, 1)) // demonstrate result
}


def biggest = { Double.POSITIVE_INFINITY }


maxRealFloat :: RealFloat a => a -> a
maxRealFloat x = encodeFloat b (e-1) `asTypeOf` x where
  b     = floatRadix x - 1
  (_,e) = floatRange x

infinity :: RealFloat a => a
infinity = if isInfinite inf then inf else maxRealFloat 1.0 where
  inf = 1/0


print, !Values.f_infinity             ;; for normal floats or
print, !Values.D_infinity             ;; for doubles


use bigint;
use ntheory qw(fromdigits todigitstring);
use feature 'say';

sub rank   { join   '', fromdigits(join('a',@_), 11) }
sub unrank { split 'a', todigitstring(@_[0],     11) }

say join ' ', @n = qw<12 11 0 7 9 15 15 5 7 13 5 5>;
say $n = rank(@n);
say join ' ', unrank $n;


without javascript_semantics
include mpfr.e

procedure rank(mpz r, sequence s)
    s = deep_copy(s)
    for i=1 to length(s) do
        s[i] = sprintf("%d",s[i])
    end for
    mpz_set_str(r,join(s,'a'),11)
end procedure

function unrank(mpz i)
    sequence res = split(mpz_get_str(i,11),'a')
    for j=1 to length(res) do
        {{res[j]}} = scanf(res[j],"%d")
    end for
    return res
end function

sequence l = {1, 2, 3, 10, 100, 987654321}
mpz n = mpz_init()
rank(n,l)
sequence u = unrank(n)
printf(1,"%V\n",{{l,mpz_get_str(n),u}})


def rank(x): return int('a'.join(map(str, [1] + x)), 11)

def unrank(n):
	s = ''
	while n: s,n = "0123456789a"[n%11] + s, n//11
	return map(int, s.split('a'))[1:]

l = [1, 2, 3, 10, 100, 987654321]
print l
n = rank(l)
print n
l = unrank(n)
print l


#define SYS_WRITE   $1
#define SYS_OPEN    $2
#define SYS_CLOSE   $3
#define SYS_FSTAT   $5
#define SYS_MMAP    $9
#define SYS_MUNMAP  $11
#define SYS_EXIT    $60

// From experiments:
#define FSIZEOFF    48
#define STATSIZE    144

// From Linux source:
#define RDONLY      $00
#define PROT_READ   $0x1
#define MAP_PRIVATE $0x02
#define STDIN       $0
#define STDOUT      $1

.global _start
.text

/* Details: */
/*
    Remember:  %rax(%rdi, %rsi, %rdx, %r10, %r8, %r9)
    - Open a file (get its fd)
        - int fd = open("filename", RDONLY)
    - Get its filesize:
        - fstat(fd, statstruct). 0 if ok. fsize at statstruct+48
    - Then memory map it.
        - void* vmemptr = mmap(vmemptr, fsize, PROT_READ, MAP_PRIVATE, fd, 0)
    - Scan for newlines, print line.
        - Keep going until done. Details at 11.
    - Unmap memory
        - munmap(vmemptr, filesize). 0 if ok.
    - Exit
 */

.macro ERRCHECK code
    cmpq    $\code, %rax
    je      fs_error
.endm

/* Local stack notes:
    0: int fd
    4: void* vmemptr
    12: void* head
    20: void* lookahead
    28: void* end
*/
_start:
    // Open:
    movq    RDONLY, %rsi
    // Filename ptr is on stack currently as argv[1]:
    cmpq    $1, (%rsp)          // if argc is 1, default to stdin
    jnz     open_file
    subq    $36, %rsp           // local stack
    movl    STDIN, (%rsp)
    jmp     fstat

    open_file:
    movq    16(%rsp), %rdi      // argc(8), argv0(8) => rsp+16. filename
    movq    SYS_OPEN, %rax
    syscall
    ERRCHECK    -1
    subq    $36, %rsp           // local stack
    movl    %eax, (%rsp)        // int fd = open(argv[1], RDONLY)

    // fstat to get filesize
    fstat:
    movq    $statstruct, %rsi
    movl    (%rsp), %edi        // fd
    movq    SYS_FSTAT, %rax
    syscall                     // fstat(fd, statstruct)
    ERRCHECK    -1

    // mmap - don't forget to munmap.
    mmap:
    movq    $0, %r9             // offset
    movq    (%rsp), %r8         // fd
    movq    MAP_PRIVATE, %r10
    movq    PROT_READ, %rdx
    movq    filesize, %rsi
    movq    (%rsp), %rdi        // vmemptr
    movq    SYS_MMAP, %rax
    syscall
    ERRCHECK    -1
    movq    %rax, 4(%rsp)       // void* vmemptr = mmap(vmemptr, fsize, PROT_READ, MAP_PRIVATE, fd, 0)

    /* Print lines */
    movq    %rax, 12(%rsp)  // head = vmemptr
    addq    filesize, %rax
    decq    %rax
    movq    %rax, 28(%rsp)  // end = vmemptr+filesize-1
    scan_outer:
        movq    12(%rsp), %rax
        cmpq    28(%rsp), %rax
        jge     cleanup         // if head >= end, done
        movq    %rax, %rbx      // Using rbx as lookahead
        scan_inner:
            cmpq    28(%rsp), %rbx
            jge     writeline       // if lookahead >= end, write the line.
            cmpb    $'\n, (%rbx)
            jz      writeline       // if '\n'==*lookahead, write the line
            incq    %rbx
            jmp     scan_inner
        writeline:
            // write:
            incq    %rbx
            movq    %rbx, %rdx
            subq    12(%rsp), %rdx  // rdx <- lookahead-head
            movq    12(%rsp), %rsi
            movq    STDOUT, %rdi
            movq    SYS_WRITE, %rax
            syscall                 // write(stdout, head, lookahead-head)
            safety:
            movq    %rbx, 12(%rsp)  // head = lookahead.
            jmp     scan_outer

    cleanup:
    // munmap
    movq    filesize, %rsi
    movq    4(%rsp), %rdi
    movq    SYS_MUNMAP, %rax
    syscall                     // munmap(vmemptr, filesize)
    cmpq    $-1, %rax
    je      fs_error
    // close
    movl    (%rsp), %edi
    movq    SYS_CLOSE, %rax
    syscall                     // close(fd)
    ERRCHECK    -1

exit:
    movq    SYS_EXIT, %rax
    xorq    %rdi, %rdi              // The exit code.
    syscall

fs_error:
    movq    SYS_EXIT, %rax
    movq    $-1, %rdi
    syscall                         // exit(-1)

.data
statstruct:     // This struct is 144 bytes. Only want size (+48)
    .zero FSIZEOFF
    filesize:  // 8 bytes.
    .quad   0
    .zero   STATSIZE-FSIZEOFF+8


int C;
[repeat                                 \read file
        repeat                          \read line
                repeat  C:= ChIn(1);    \read word
                        ChOut(0, C);
                until   (C<^A ! C>^z) & (C<^0 ! C>^9);  \non-alphanumeric
        until   C < $20;                \CR, LF, or EOF
until   C = \EOF\ $1A;
]


foreach line in (File("foo.txt")){...}
List(1,2,3).readln() // here, a "line" is a list element
Utils.Helpers.zipWith(False, // enumerate a file
   fcn(n,line){"%3d: %s".fmt(n,line).print()},[1..],File("cmp.zkl"))


   _ * 5 NB. multiplying infinity to 5 results in infinity
_
   5 % _ NB. dividing 5 by infinity results in 0
0
   5 % 0 NB. dividing 5 by 0 results in infinity
_


double infinity = Double.POSITIVE_INFINITY; //defined as 1.0/0.0
Double.isInfinite(infinity); //true


  [ $ "" swap
    witheach
      [ number$
        char A join join ]
    11 base put
    $->n drop
    base release ]         is rank   ( [ --> n )

  [ 11 base put
    number$
    base release
    [] $ "" rot
    witheach
      [ dup char A = iff
          [ drop
            $->n drop join
            $ "" ]
        else join ]
    drop ]                 is unrank ( n --> [ )


#lang racket/base
(require (only-in racket/string string-join string-split))

(define (integer->octal-string i)
  (number->string i 8))

(define (octal-string->integer s)
  (string->number s 8))

(define (rank is)
  (string->number (string-join (map integer->octal-string is) "8")))

(define (unrank ranking)
  (map octal-string->integer (string-split (number->string ranking 10) "8")))

(module+ test
  (define loi '(1 2 3 10 100 987654321 135792468107264516704251 7))
  (define rnk (rank loi))
  (define urk (unrank rnk))
  (displayln loi)
  (displayln rnk)
  (displayln urk))


sub rank(*@n)      { :11(@n.join('A')) }
sub unrank(Int $n) { $n.base(11).split('A') }

say my @n = (1..20).roll(12);
say my $n = rank(@n);
say unrank $n;


/*REXX program assigns an integer for a finite list of arbitrary non-negative integers. */
parse arg $                                      /*obtain optional argument  (int list).*/
if $='' | $=","  then $=3 14 159 265358979323846 /*Not specified?  Then use the default.*/
                                                 /* [↑]  kinda use decimal digits of pi.*/
$= translate( space($),   ',',   " ")            /*use a  commatized  list of integers. */
numeric digits max(9, 2 * length($) )            /*ensure enough dec. digits to handle $*/

                 say 'original list='   $        /*display the original list of integers*/
N=   rank($);    say '  map integer='   N        /*generate and display the map integer.*/
O= unrank(N);    say '       unrank='   O        /*generate original integer and display*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
rank:    return    x2d( translate( space( arg(1) ),  'c',  ",") )
unrank:  return  space( translate(   d2x( arg(1) ),  ',',  "C") )


def rank(arr)
  arr.join('a').to_i(11)
end

def unrank(n)
  n.to_s(11).split('a').map(&:to_i)
end

l = [1, 2, 3, 10, 100, 987654321]
p l
n = rank(l)
p n
l = unrank(n)
p l


julia> julia> Inf32 == Inf64 == Inf16 == Inf
true


   / Integer infinities
   / 0I is just 2147483647
   / -0I is just -2147483647
   / -2147483648 is a special "null integer"(NaN) 0N
   0I*0I
1
   0I-0I
0
   0I+1
0N
   0I+2
-0I
   0I+3 / -0I+1
-2147483646
   0I-1
2147483646
   0I%0I
1
   0I^2
4.611686e+18
   0I^0I
0i
   0I^-0I
0.0
   1%0
0I
   0%0
0
   0i^2
0i
   0i^0i
0i

   / Floating point infinities in K are something like
   / IEEE 754 values
   / Also there is floating point NaN -- 0n
   0i+1
0i
   0i*0i
0i
   0i-0i
0n
   0i%0i
0n
   0i%0n
0n
   / but
   0.0%0.0
0.0


1e300 dup mult tostr "inf" equal ["Infinity" print] if

" " input


fun main(args: Array<String>) {
    val p = Double.POSITIVE_INFINITY // +∞
    println(p.isInfinite()) // true
    println(p.isFinite()) // false
    println("${p < 0} ${p > 0}")  // false true

    val n = Double.NEGATIVE_INFINITY // -∞
    println(n.isInfinite()) // true
    println(n.isFinite()) // false
    println("${n < 0} ${n > 0}")  // true false
}


{/ 1 0}
-> Infinity
{/ 1 Infinity}
-> 0
{< {pow 10 100} Infinity}
-> true
{< {pow 10 1000} Infinity}
-> false


object IndexFiniteList extends App {
  val (defBase, s) = (10, Seq(1, 2, 3, 10, 100, 987654321))

  def rank(x: Seq[Int], base: Int = defBase) =
    BigInt(x.map(Integer.toString(_, base)).mkString(base.toHexString), base + 1)

  def unrank(n: BigInt, base: Int = defBase): List[BigInt] =
    n.toString(base + 1).split((base).toHexString).map(BigInt(_)).toList

  val ranked = rank(s)

  println(s.mkString("[", ", ", "]"))
  println(ranked)
  println(unrank(ranked).mkString("[", ", ", "]"))

}


func rank(Array arr) {
    Number(arr.join('a'), 11)
}

func unrank(Number n) {
    n.base(11).split('a').map { Num(_) }
}

var l = [1, 2, 3, 10, 100, 987654321]
say l
var n = rank(l)
say n
var l = unrank(n)
say l


package require Tcl 8.6

proc rank {integers} {
    join [lmap i $integers {format %llo $i}] 8
}

proc unrank {codedValue} {
    lmap i [split $codedValue 8] {scan $i %llo}
}


import "/big" for BigInt

// Separates each integer in the list with an 'a' then encodes in base 11.
// Empty list mapped to '-1'.
var rank = Fn.new { |li|
    if (li.count == 0) return BigInt.minusOne
    return BigInt.fromBaseString(li.join("a"), 11)
}

var unrank = Fn.new { |r|
    if (r == BigInt.minusOne) return []
    return r.toBaseString(11).split("a").map { |d| (d != "") ? Num.fromString(d) : 0 }.toList
}

// Each integer n in the list mapped to '1' plus n '0's.
// Empty list mapped to '0'
var rank2 = Fn.new { |li|
    if (li.isEmpty) return BigInt.zero
    var sb = ""
    for (i in li) sb = sb + "1" + ("0" * i)
    return BigInt.fromBaseString(sb, 2)
}

var unrank2 = Fn.new { |r|
    if (r == BigInt.zero) return []
    return r.toBaseString(2)[1..-1].split("1").map { |d| d.count }.toList
}

var li = [0, 1, 2, 3, 10, 100, 987654321]
System.print("Before ranking  : %(li)")
var r = rank.call(li)
System.print("Rank = %(r)")
li = unrank.call(r)
System.print("After unranking : %(li)")
System.print("\nAlternative approach (not suitable for large numbers)...\n")
li = li[0..-2]
System.print("Before ranking  : %(li)")
r = rank2.call(li)
System.print("Rank = %(r)")
li = unrank2.call(r)
System.print("After unranking : %(li)")


function infinity()
  return 1/0 --lua uses unboxed C floats for all numbers
end


Rem : locale 1033
Module CheckIt {
      Form 66,40
      Cls 5
      Pen 14
      \\ Ensure True/False for Print boolean (else -1/0)
      \\ from m2000 console use statement Switches without Set.
      \\ use Monitor statement to see all switches.
      Set Switches "+SBL"
      IF version<9.4 then exit
      IF version=9.4 and revision<25 then exit
      Function Infinity(positive=True) {
            buffer clear inf as byte*8
            m=0x7F
            if not positive then m+=128
            return inf, 7:=m, 6:=0xF0
            =eval(inf, 0 as double)
      }
      K=Infinity(false)
      L=Infinity()
      Function TestNegativeInfinity(k) {
            =str$(k, 1033) = "-1.#INF"
      }
      Function TestPositiveInfinity(k) {
            =str$(k, 1033) = "1.#INF"
      }
      Function TestInvalid {
            =str$(Number, 1033) = "-1.#IND"
      }
      Pen 11 {Print "       True       True"}
      Print TestNegativeInfinity(K), TestPositiveInfinity(L)
      Pen 11 {Print "    -1.#INF     1.#INF    -1.#INF     1.#INF    -1.#INF     1.#INF"}
      Print K, L, K*100, L*100, K+K, L+L
      M=K/L
      Pen 11 {Print "    -1.#IND    -1.#IND       True       True" }
      Print K/L, L/K, TestInvalid(M), TestInvalid(K/L)
      M=K+L
      Pen 11 {Print  "    -1.#IND    -1.#IND    -1.#IND       True       True"}
      Print M, K+L, L+K, TestInvalid(M), TestInvalid(K+L)
      Pen 11 {Print "    -1.#INF     1.#INF"}
      Print 1+K+2, 1+L+2
      Pen 11 {Print "    -1.#INF"}
      Print K-L
      Pen 11 {Print "     1.#INF"}
      Print L-K
}
Checkit


> proc() Float(infinity) end();
                            Float(infinity)


Sum[1/n^2,{n,Infinity}]
1/Infinity
Integrate[Exp[-x^2], {x, -Infinity, Infinity}]
10^100 < Infinity


var BN=Import("zklBigNum");
fcn rank(ns)   { BN(ns.concat("A"),11) }
fcn unrank(bn) { bn.toString(11).split("a").apply("toInt") }
fcn unrankS(bn){ bn.toString(11).split("a") }


/* Maxima has inf (positive infinity) and minf (negative infinity) */

declare(x, real)$

is(x < inf);
/* true */

is(x > minf);
/* true */

/* However, it is an error to try to divide by zero, even with floating-point numbers */
1.0/0.0;
/* expt: undefined: 0 to a negative exponent.
   -- an error. To debug this try: debugmode(true); */


MODULE inf;

IMPORT  InOut;

BEGIN
  InOut.WriteReal (1.0 / 0.0, 12, 12);
  InOut.WriteLn
END inf.


MODULE Inf EXPORTS Main;

IMPORT IO, IEEESpecial;

BEGIN
  IO.PutReal(IEEESpecial.RealPosInf);
  IO.Put("\n");
END Inf.


def posinf = double.PositiveInfinity;
def a = IsInfinity(posinf);         // a = true
def b = IsNegativeInfinity(posinf); // b = false
def c = IsPositiveInfinity(posinf); // c = true


10 1000.0 powf dup println dup neg println 1 swap / println


+inf.0 ; positive infinity
-inf.0 ; negative infinity


print 1.5e-400 '0

print 1.5e400  '#INF

print -1.5e400 '#-INF

print 0/-1.5   '-0

print 1.5/0    '#INF

print -1.5/0   '#-INF

print 0/0      '#qNAN

function f() as double
return -1.5/0
end function

print f '#-INF


declare
  PosInf = 1./0.
  NegInf = ~1./0.
in
  {Show PosInf}
  {Show NegInf}

  %% some assertion
  42. / PosInf = 0.
  42. / NegInf = 0.
  PosInf * PosInf = PosInf
  PosInf * NegInf = NegInf
  NegInf * NegInf = PosInf


with javascript_semantics
constant infinity = 1e300*1e300
? infinity


1e300 dup * tostr "inf" == if "Infinity" print endif


declare x float, y float (15), z float (18);

put skip list (huge(x), huge(y), huge(z));


function infinity {
    [double]::PositiveInfinity
}


If OpenConsole()
  Define.d a, b
  b = 0

  ;positive infinity
  PrintN(StrD(Infinity())) ;returns the value for positive infinity from builtin function

  a = 1.0
  PrintN(StrD(a / b)) ;calculation results in the value of positive infinity

  ;negative infinity
  PrintN(StrD(-Infinity())) ;returns the value for negative infinity from builtin function

  a = -1.0
  PrintN(StrD(a / b)) ;calculation results in the value of negative infinity

  Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf


#include<math.h>
//save as inf.h
double inf(void){
	return HUGE_VAL;
}


DECLARE FUNCTION f! ()

ON ERROR GOTO TratoError
PRINT 0!
PRINT 0 / -1.5
PRINT 1.5 / 0
PRINT 0 / 0
PRINT f
END

TratoError:
PRINT "Error "; ERR; " on line "; ERL; CHR$(9); " --> ";
SELECT CASE ERR
CASE 6
    PRINT "Overflow"
    RESUME NEXT
CASE 11
    PRINT "Division by zero"
    RESUME NEXT
CASE ELSE
    PRINT "Unexpected error, ending program."
    END
END SELECT

FUNCTION f!
    f! = -1.5 / 0
END FUNCTION


 Inf                    #positive infinity
 -Inf                   #negative infinity
 .Machine$double.xmax   # largest finite floating-point number
 is.finite              # function to test to see if a number is finite

# function that returns the input if it is finite, otherwise returns (plus or minus) the largest finite floating-point number
 forcefinite <- function(x) ifelse(is.finite(x), x, sign(x)*.Machine$double.xmax)

 forcefinite(c(1, -1, 0, .Machine$double.xmax, -.Machine$double.xmax, Inf, -Inf))
# [1]   1.000000e+00  -1.000000e+00   0.000000e+00  1.797693e+308
# [5] -1.797693e+308  1.797693e+308 -1.797693e+308


#lang racket

+inf.0 ; positive infinity
(define (finite? x) (< -inf.0 x +inf.0))
(define (infinite? x) (not (finite? x)))


my $x = 1.5/0;       # Failure: catchable error, if evaluated will return: "Attempt to divide by zero ...
my $y = (1.5/0).Num; # assigns 'Inf'


For the default setting of

               NUMERIC DIGITS 9

the biggest number that can be used is  (for the Regina REXX  and  R4  REXX interpreters):

.999999999e+999999999


a = 1.0/0       # => Infinity
a.finite?       # => false
a.infinite?     # => 1

a = -1/0.0      # => -Infinity
a.infinite?     # => -1

a = Float::MAX  # => 1.79769313486232e+308
a.finite?       # => true
a.infinite?     # => nil


fn main() {
    let inf = f32::INFINITY;
    println!("{}", inf);
}


val inf = Double.PositiveInfinity //defined as 1.0/0.0
inf.isInfinite; //true


+inf.0 ; positive infinity
(define (finite? x) (< -inf.0 x +inf.0))
(define (infinite? x) (not (finite? x)))


var a = 1.5/0        # Inf
say a.is_inf         # true
say a.is_pos         # true

var b = -1.5/0       # -Inf
say b.is_ninf        # true
say b.is_neg         # true

var inf = Inf
var ninf = -Inf
say (inf == -ninf)   # true


st> FloatD infinity
Inf
st> 1.0 / 0.0
Inf


let inf = Double.infinity
inf.isInfinite //true


package require Tcl 8.5

expr {1.0 / 0}  ;# ==> Inf
expr {-1.0 / 0} ;# ==> -Inf
expr {inf}      ;# ==> Inf
expr {1 / 0}    ;# ==> "divide by zero" error; Inf not part of range of integer division


: inf 1.0 0.0 / ;
: -inf inf neg ;
: inf? abs inf = ;


Option Explicit

Private Declare Sub GetMem8 Lib "msvbvm60.dll" _
  (ByVal SrcAddr As Long, ByVal TarAddr As Long)

Sub Main()
Dim PlusInfinity As Double
Dim MinusInfinity As Double
Dim IndefiniteNumber As Double
    On Error Resume Next
    PlusInfinity = 1 / 0
    MinusInfinity = -1 / 0
    IndefiniteNumber = 0 / 0
    Debug.Print "PlusInfinity     = " & CStr(PlusInfinity) _
      & "  (" & DoubleAsHex(PlusInfinity) & ")"
    Debug.Print "MinusInfinity    = " & CStr(MinusInfinity) _
      & " (" & DoubleAsHex(MinusInfinity) & ")"
    Debug.Print "IndefiniteNumber = " & CStr(IndefiniteNumber) _
      & " (" & DoubleAsHex(IndefiniteNumber) & ")"
End Sub

Function DoubleAsHex(ByVal d As Double) As String
Dim l(0 To 1) As Long
GetMem8 VarPtr(d), VarPtr(l(0))
DoubleAsHex = Right$(String$(8, "0") & Hex$(l(1)), 8) _
            & Right$(String$(8, "0") & Hex$(l(0)), 8)
End Function


import math

fn main() {
    mut x := 1.5 // type of x determined by literal
    // that this compiles demonstrates that PosInf returns same type as x,
    // the type specified by the task.
    x = math.inf(1)
    println('$x ${math.is_inf(x, 1)}') // demonstrate result
}


var x = 1.5
var y = x / 0
System.print("x = %(x)")
System.print("y = %(y)")
System.print("'x' is infinite?  %(x.isInfinity)")
System.print("'y' is infinite?  %(y.isInfinity)")


int  A;
real X;
[Format(0, 15);         \output in scientific notation
A:= addr X;             \get address of (pointer to) X
A(0):= $FFFF_FFFF;      \stuff in largest possible value
A(1):= $7FEF_FFFF;
RlOut(0, X);            \display it
]


infinity = 1e300*1e300
if str$(infinity) = "inf" print "Infinity"


const std = @import("std");

const debug = std.debug;
const math = std.math;

test "infinity" {
    const infinite_f16 = math.inf(f16);
    const infinite_f32 = math.inf(f32);
    const infinite_f64 = math.inf(f64);
    const infinite_f128 = math.inf(f128);

    // Any other types besides these four floating types are not implemented.

    debug.assert(math.isInf(infinite_f16));
    debug.assert(math.isInf(infinite_f32));
    debug.assert(math.isInf(infinite_f64));
    debug.assert(math.isInf(infinite_f128));

    debug.assert(math.isPositiveInf(infinite_f16));
    debug.assert(math.isPositiveInf(infinite_f32));
    debug.assert(math.isPositiveInf(infinite_f64));
    debug.assert(math.isPositiveInf(infinite_f128));

    debug.assert(math.isNegativeInf(-infinite_f16));
    debug.assert(math.isNegativeInf(-infinite_f32));
    debug.assert(math.isNegativeInf(-infinite_f64));
    debug.assert(math.isNegativeInf(-infinite_f128));

    debug.assert(!math.isFinite(infinite_f16));
    debug.assert(!math.isFinite(infinite_f32));
    debug.assert(!math.isFinite(infinite_f64));
    // isFinite(f128) is not implemented.
    //debug.assert(!math.isFinite(infinite_f128));
}


F digit_sum(=n, =sum)
   sum++
   L n > 0 & n % 10 == 0
      sum -= 9
      n /= 10
   R sum

V previous = 1
V gap = 0
V s = 0
V niven_index = 0
V gap_index = 1

print(‘Gap index  Gap    Niven index    Niven number’)

V niven = 1

L gap_index <= 22
   s = digit_sum(niven, s)
   I niven % s == 0
      I niven > previous + gap
         gap = niven - previous
         print(‘#9 #4  #13     #11’.format(gap_index, gap, niven_index, previous))
         gap_index++
      previous = niven
      niven_index++
   niven++


BEGIN # show where the gaps increase in the series of Niven numbers #
      # ( numbers divisible by the sum of their digits ) #
    INT n count := 0;
    INT g count := 0;
    INT n gap   := 0;
    INT this n  := 1;
    print( ( "  Gap   Gap    Niven     Niven Next",         newline ) );
    print( ( "Index Value    Index    Number Niven Number", newline ) );
    print( ( "----- ----- -------- --------- ------------", newline ) );
    INT t8 := 0;
    FOR d0 FROM 0 TO 9 DO
        FOR d1 FROM 0 TO 9 DO
            INT s1  = d0 + d1;
            FOR d2 FROM 0 TO 9 DO
                INT s2  = s1 + d2;
                FOR d3 FROM 0 TO 9 DO
                    INT s3  = s2 + d3;
                    FOR d4 FROM 0 TO 9 DO
                        INT s4  = s3 + d4;
                        FOR d5 FROM 0 TO 9 DO
                            INT s5  = s4 + d5;
                            FOR d6 FROM 0 TO 9 DO
                                INT s6  = s5 + d6;
                                FOR d7 FROM 0 TO 9 DO
                                    INT s7  = s6 + d7;
                                    FOR d8 FROM 0 TO 9 DO
                                        INT s8  = s7 + d8;
                                        IF s8 /= 0 THEN
                                            t8 +:= 1;
                                            IF t8 MOD s8 = 0 THEN
                                                # have a Niven number #
                                                INT this gap = t8 - this n;
                                                IF this gap > n gap THEN
                                                    # found a larger gap #
                                                    g count +:= 1;
                                                    n gap    := this gap;
                                                    print( ( whole( g count, -5 )
                                                           , whole( n gap,   -6 )
                                                           , whole( n count, -9 )
                                                           , whole( this n, -10 )
                                                           , " "
                                                           , whole( t8,       0 )
                                                           , newline
                                                           )
                                                         )
                                                FI;
                                                n count +:= 1;
                                                this n   := t8
                                            FI
                                        FI
                                    OD # d8 #
                                OD # d7 #
                            OD # d6 #
                        OD # d5 #
                    OD # d4 #
                OD # d3 #
            OD # d2 #
        OD # d1 #
    OD # d0 #
END


# syntax: GAWK -f INCREASING_GAPS_BETWEEN_CONSECUTIVE_NIVEN_NUMBERS.AWK
# converted from C
BEGIN {
    gap_index = 1
    previous = 1
    print("Gap index  Gap  Niven index  Niven number")
    print("---------  ---  -----------  ------------")
    for (niven=1; gap_index<=22; niven++) {
      sum = digit_sum(niven,sum)
      if (divisible(niven,sum)) {
        if (niven > previous + gap) {
          gap = niven - previous
          printf("%9d %4d %12d %13d\n",gap_index++,gap,niven_index,previous)
        }
        previous = niven
        niven_index++
      }
    }
    exit(0)
}
function digit_sum(n,sum) {
# returns the sum of the digits of n given the sum of the digits of n - 1
    sum++
    while (n > 0 && n % 10 == 0) {
      sum -= 9
      n = int(n / 10)
    }
    return(sum)
}
function divisible(n,d) {
    if (and(d,1) == 0 && and(n,1) == 1) {
      return(0)
    }
    return(n % d == 0)
}


function digit_sum(n, sum)
	# devuelve la suma de los dígitos de n dada la suma de los dígitos de n - 1
	sum ++
	while (n > 0 and n mod 10 = 0)
		sum -= 9
		n = int(n / 10)
	end while
	return sum
end function

function divisible(n, d)
	if ((d mod 1) = 0) and ((n mod 1) = 1) then
		return 0
	end if
	return (n mod d = 0)
end function

global sum
sum = 0
gap = 0 : niven = 0 : niven_index = 0
gap_index = 0
previous  = 1
print "Gap index    Gap      Niven index     Niven number"
print "---------    ---      -----------     ------------"

for niven = 1 to 1000000
	sum = digit_sum(niven, sum)
	if divisible(niven, sum) then
		if (niven > previous + gap) then
			gap_index += 1
			gap = niven - previous
			print gap_index, gap, niven_index, previous
		end if
		previous = niven
		niven_index ++
	end if
next niven
end


#include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

// Returns the sum of the digits of n given the
// sum of the digits of n - 1
uint64_t digit_sum(uint64_t n, uint64_t sum) {
    ++sum;
    while (n > 0 && n % 10 == 0) {
        sum -= 9;
        n /= 10;
    }
    return sum;
}

inline bool divisible(uint64_t n, uint64_t d) {
    if ((d & 1) == 0 && (n & 1) == 1)
        return false;
    return n % d == 0;
}

int main() {
    setlocale(LC_ALL, "");

    uint64_t previous = 1, gap = 0, sum = 0;
    int niven_index = 0, gap_index = 1;

    printf("Gap index  Gap    Niven index    Niven number\n");
    for (uint64_t niven = 1; gap_index <= 32; ++niven) {
        sum = digit_sum(niven, sum);
        if (divisible(niven, sum)) {
            if (niven > previous + gap) {
                gap = niven - previous;
                printf("%'9d %'4llu %'14d %'15llu\n", gap_index++,
                       gap, niven_index, previous);
            }
            previous = niven;
            ++niven_index;
        }
    }
    return 0;
}


#include <cstdint>
#include <iomanip>
#include <iostream>

// Returns the sum of the digits of n given the
// sum of the digits of n - 1
uint64_t digit_sum(uint64_t n, uint64_t sum) {
    ++sum;
    while (n > 0 && n % 10 == 0) {
        sum -= 9;
        n /= 10;
    }
    return sum;
}

inline bool divisible(uint64_t n, uint64_t d) {
    if ((d & 1) == 0 && (n & 1) == 1)
        return false;
    return n % d == 0;
}

int main() {
    // Print numbers with commas
    std::cout.imbue(std::locale(""));

    uint64_t previous = 1, gap = 0, sum = 0;
    int niven_index = 0, gap_index = 1;

    std::cout << "Gap index  Gap    Niven index    Niven number\n";
    for (uint64_t niven = 1; gap_index <= 32; ++niven) {
        sum = digit_sum(niven, sum);
        if (divisible(niven, sum)) {
            if (niven > previous + gap) {
                gap = niven - previous;
                std::cout << std::setw(9) << gap_index++
                    << std::setw(5) << gap
                    << std::setw(15) << niven_index
                    << std::setw(16) << previous << '\n';
            }
            previous = niven;
            ++niven_index;
        }
    }
    return 0;
}


include "cowgol.coh";

# print uint32 right-aligned in column, with
# thousands separators
sub print_col(num: uint32, width: uint8) is
    # maximum integer is 4,294,967,296 for length 13,
    # plus one extra for the zero terminator
    var buf: uint8[14];
    var start := &buf[0];
    var last := UIToA(num, 10, &buf[0]);

    # right-align and add separators
    var right := &buf[13];
    var th: uint8 := 3;
    while last >= start loop
        [right] := [last];
        right := @prev right;
        last := @prev last;
        if th == 0 and last >= start then
            # add separator every 3 characters
            [right] := ',';
            right := @prev right;
            th := 2;
        else
            th := th - 1;
        end if;
    end loop;

    # print the result and spaces
    var size := (13 - (right - start)) as uint8;
    while width >= size loop
        print_char(' ');
        width := width-1;
    end loop;
    print(@next right);
end sub;

# returns sum of digits of n, given sum of digits of n-1
sub digit_sum(n: uint32, prev: uint32): (sum: uint32) is
    sum := prev + 1;
    while n > 0 and n % 10 == 0 loop
        sum := sum - 9;
        n := n / 10;
    end loop;
end sub;

var prev: uint32 := 1;
var gap: uint32 := 0;
var sum: uint32 := 0;
var idx: uint32 := 0;
var gap_idx: uint8 := 1;
var niven: uint32 := 1;

print("Gap index  Gap    Niven index    Niven number\n");
while gap_idx <= 27 loop
    sum := digit_sum(niven, sum);
    if (not (sum & 1 == 0 and niven & 1 == 1))
    and (niven % sum == 0) then
        if niven > prev + gap then
            gap := niven - prev;
            print_col(gap_idx as uint32, 9);
            gap_idx := gap_idx + 1;
            print_col(gap, 5);
            print_col(idx, 15);
            print_col(prev, 16);
            print_nl();
        end if;
        prev := niven;
        idx := idx + 1;
    end if;
    niven := niven + 1;
end loop;


       program nivengaps
       implicit none
       integer*8 prev /1/, gap /0/, sum /0/
       integer*8 nividx /0/, niven /1/
       integer gapidx /1/

       character*13 idxfmt
       character*14 nivfmt
       write (*,*) 'Gap no  Gap   Niven index    Niven number '
       write (*,*) '------  ---  -------------  --------------'

 10    call divsum(niven, sum)
       if (mod(niven, sum) .EQ. 0) then
          if (niven .GT. prev + gap) then
             gap = niven - prev
             call fmtint(nividx,13,idxfmt)
             call fmtint(prev,14,nivfmt)
             write (*,20) gapidx,gap,idxfmt,nivfmt
             gapidx = gapidx + 1
          end if
          prev = niven
          nividx = nividx + 1
       end if
       niven = niven + 1
       if (gapidx .LE. 32) go to 10

       stop
 20    format (i7,'  ',i3,'  ',a13,'  ',a14)
       end program

C      Sum of divisors of NN, given the sum of divisors of NN-1
       subroutine divsum(nn,sum)
          implicit none
          integer*8 n,nn,sum
          n = nn
          sum = sum + 1
 30       if (n.GT.0 .AND. mod(n,10).EQ.0) then
             sum = sum - 9
             n = n / 10
             go to 30
          end if
       end subroutine

       integer*8 function mod(a,b)
          implicit none
          integer*8 a,b
          mod = a - a/b * b
       end function

C      Format a positive integer with ',' as the thousands separator.
       subroutine fmtint(num, len, str)
          implicit none
          integer*8 n, num
          integer pos, len, th
          character(*) str
          n=num
          pos=len
          th=2
 40       if (pos.GT.0) then
             if (n.EQ.0) then
                str(pos:pos) = ' '
             else
                str(pos:pos) = achar(mod(n,10) + iachar('0'))
                if (th.EQ.0 .AND. n.GE.10 .AND. pos.GT.1) then
                    th = 2
                    pos = pos-1
                    str(pos:pos) = ','
                else
                    th = th-1
                end if
            end if
            pos = pos - 1
            n = n/10
            go to 40
          end if
       end subroutine


Function digit_sum(n As Uinteger, sum As Ulong) As Ulong
    ' devuelve la suma de los dígitos de n dada la suma de los dígitos de n - 1
    sum += 1
    While (n > 0 And n Mod 10 = 0)
        sum -= 9
        n = Int(n / 10)
    Wend
    Return sum
End Function

Function divisible(n As Uinteger, d As Uinteger) As Boolean
    If ((d Mod 1) = 0) And ((n Mod 1) = 1) Then
        Return 0
    End If
    Return (n Mod d = 0)
End Function

Dim As Ulong gap_index = 0
Dim As Ulong previous  = 1
Dim As Uinteger gap
Dim As Ulong niven_index
Print "Gap index  Gap  Niven index  Niven number"
Print "---------  ---  -----------  ------------"

For niven As Uinteger = 1 To 100000000
    Dim As Ulong sum = digit_sum(niven,sum)
    If divisible(niven, sum) Then
        If (niven > previous + gap) Then
            gap_index += 1
            gap = niven - previous
            Print Using "#########  ###  ###,###,###  ####,###,###"; gap_index; gap; niven_index; previous
        End If
        previous = niven
        niven_index += 1
    End If
Next niven
Sleep


package main

import "fmt"

type is func() uint64

func newSum() is {
    var ms is
    ms = func() uint64 {
        ms = newSum()
        return ms()
    }
    var msd, d uint64
    return func() uint64 {
        if d < 9 {
            d++
        } else {
            d = 0
            msd = ms()
        }
        return msd + d
    }
}

func newHarshard() is {
    i := uint64(0)
    sum := newSum()
    return func() uint64 {
        for i++; i%sum() != 0; i++ {
        }
        return i
    }
}

func commatize(n uint64) string {
    s := fmt.Sprintf("%d", n)
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    return s
}

func main() {
    fmt.Println("Gap    Index of gap   Starting Niven")
    fmt.Println("===   =============   ==============")
    h := newHarshard()
    pg := uint64(0) // previous highest gap
    pn := h()       // previous Niven number
    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {
        g := n - pn
        if g > pg {
            fmt.Printf("%3d   %13s   %14s\n", g, commatize(i), commatize(pn))
            pg = g
        }
        pn = n
    }
}


{-# LANGUAGE NumericUnderscores #-}
import Control.Monad (guard)
import Text.Printf (printf)
import Data.List (intercalate, unfoldr)
import Data.List.Split (chunksOf)
import Data.Tuple (swap)

nivens :: [Int]
nivens = [1..] >>= \n -> guard (n `rem` digitSum n == 0) >> [n]
 where
  digitSum = sum . unfoldr (\x -> guard (x > 0) >> pure (swap $ x `quotRem` 10))

findGaps :: [(Int, Int, Int)]
findGaps = go (zip [1..] nivens) 0
 where
  go [] n = []
  go r@((c, currentNiven):(_, nextNiven):xs) lastGap
   | gap > lastGap = (gap, c, currentNiven) : go (tail r) gap
   | otherwise     = go (tail r) lastGap
   where
    gap = nextNiven - currentNiven
  go (x:xs) _ = []

thousands :: Int -> String
thousands = reverse . intercalate "," . chunksOf 3 . reverse . show

main :: IO ()
main = do
  printf row "Gap" "Index of Gap" "Starting Niven"
  mapM_ (\(gap, gapIndex, niven) -> printf row (show gap) (thousands gapIndex) (thousands niven))
    $ takeWhile (\(_, gapIndex, _) -> gapIndex < 10_000_000) findGaps
 where
  row = "%5s%15s%15s\n"


tasks=: (gap , (,:~ index))@:niven

gap=: 0 ,~ 2 -~/\ ]
index=: [email protected]:#
niven=: [email protected]:[email protected]:i.
nivenQ=: 0 = (|~ ([: (+/"1) 10&#.^:_1))

assert 1 0 1 -: nivenQ 10 11 12   NB. demonstrate correct niven test
assert 1 = +/ 10 12 E. niven 100  NB. the sublist 10 12 occurs once in niven numbers less than 100
assert 0 1 6 90 -: gap 1 2 8 98   NB. show infix swapped subtractions


public class NivenNumberGaps {

    //  Title:  Increasing gaps between consecutive Niven numbers

    public static void main(String[] args) {
        long prevGap = 0;
        long prevN = 1;
        long index = 0;
        System.out.println("Gap      Gap Index   Starting Niven");
        for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {
            if ( isNiven(n) ) {
                index++;
                long curGap = n - prevN;
                if ( curGap > prevGap ) {
                    System.out.printf("%3d  %,13d  %,15d%n", curGap, index, prevN);
                    prevGap = curGap;
                }
                prevN = n;
            }
        }
    }

    public static boolean isNiven(long n) {
        long sum = 0;
        long nSave = n;
        while ( n > 0 ) {
            sum += n % 10;
            n /= 10;
        }
        return nSave % sum == 0;
    }

}


using Formatting

function findharshadgaps(N)
    isharshad(i) = i % sum(digits(i)) == 0
    println("Gap Index  Number Index  Niven Number")
    lastnum, lastnumidx, biggestgap = 1, 1, 0
    for i in 2:N
        if isharshad(i)
            if (gap = i - lastnum) > biggestgap
                println(lpad(gap, 5), lpad(format(lastnumidx, commas=true), 14),
                    lpad(format(lastnum, commas=true), 18))
                biggestgap = gap
            end
            lastnum, lastnumidx = i, lastnumidx + 1
        end
    end
end

findharshadgaps(50_000_000_000)


            NORMAL MODE IS INTEGER

            INTERNAL FUNCTION REM.(A,B) = A-A/B*B

            PRINT COMMENT $ GAP NO  GAP  NIVEN INDEX  NIVEN NUMBER$
            PRINT COMMENT $ ******  ***  ***********  ************$
            VECTOR VALUES FMT = $I6,S2,I3,S2,I11,S2,I12*$

            PREV = 1
            GAP = 0
            SUM = 0
            NIVIX = 0
            GAPIX = 1

            THROUGH LOOP, FOR NIVEN=1, 1, GAPIX.G.22
            SUM = SUM + 1
            N = NIVEN
DSUM        WHENEVER N.G.0 .AND. REM.(N,10).E.0
                SUM = SUM - 9
                N = N / 10
                TRANSFER TO DSUM
            END OF CONDITIONAL
            WHENEVER REM.(NIVEN,SUM).E.0
                WHENEVER NIVEN.G.PREV+GAP
                    GAP = NIVEN-PREV
                    PRINT FORMAT FMT,GAPIX,GAP,NIVIX,PREV
                    GAPIX = GAPIX + 1
                END OF CONDITIONAL
                PREV = NIVEN
                NIVIX = NIVIX + 1
            END OF CONDITIONAL
LOOP        CONTINUE

            END OF PROGRAM


ClearAll[NivenQ]
$HistoryLength = 0;
NivenQ[n_Integer] := Divisible[n, Total[IntegerDigits[n]]]
sel = Select[Range[100000000], NivenQ];
i = FoldPairList[{#2 > #1, Max[#1, #2]} &, 0, Differences[sel]];
gapindex = Range[Count[i, True]];
nivenindex = Pick[Range[Length[i]], i];
nivennumber = Pick[Most[sel], i];
gap = sel[[nivenindex + 1]] - sel[[nivenindex]];
Grid[{gapindex, gap, nivenindex, nivennumber} // Transpose // Prepend[{"gap index", "gap", "niven index", "niven number"}], Frame -> All]


import strformat

func digitsSum(n, sum: uint64): uint64 =
  ## Returns the sum of the digits of n given the sum of the digits of n - 1.
  result = sum + 1
  var n = n
  while n > 0 and n mod 10 == 0:
    dec result, 9
    n = n div 10

func divisible(n, d: uint64): bool {.inline.} =
  if (d and 1) == 0 and (n and 1) == 1:
    return false
  result = n mod d == 0

when isMainModule:

  echo "Gap index  Gap  Niven index  Niven number"

  var
    niven, gap, sum, nivenIndex = 0u64
    previous, gapIndex = 1u64

  while gapIndex <= 32:
    inc niven
    sum = digitsSum(niven, sum)
    if divisible(niven, sum):
      if niven > previous + gap:
        gap = niven - previous
        echo fmt"{gapIndex:9d} {gap:4d} {nivenIndex:12d} {previous:13d}"
        inc gapIndex
      previous = niven
      inc nivenIndex


program NivenGaps;
{$IFDEF FPC}
  {$MODE DELPHI}
  {$OPTIMIZATION ON,ALL}
{$ELSE}
  {$APPTYPE DELPHI}
{$ENDIF}
uses
  sysutils,
  strutils;
const
  base = 10;
type
  tNum      = Uint64;
const
  cntbasedigits = ((trunc(ln(High(tNum))/ln(base))+1) DIV 8 +1) *8;
type
  tSumDigit = record
                sdDigits  : array[0..cntbasedigits-1] of byte;
                sdNumber,
                sdNivCount,
                sdSumDig  : tNum;
                sdIsNiven : boolean;
              end;
var
  MySumDig : tSumDigit;

procedure OutNivenGap(ln,num,delta:TNum);
Begin
  writeln(delta:3,Numb2USA(IntToStr(MySumDig.sdNivCount-1)):16,
          Numb2USA(IntToStr(ln)):17);
end;

function InitSumDigit( n : tNum):tSumDigit;
var
  sd : tSumDigit;
  qt : tNum;
  i  : NativeInt;
begin
  with sd do
  begin
    sdNumber:= n;
    fillchar(sdDigits,SizeOf(sdDigits),#0);
    sdSumDig :=0;
    sdIsNiven := false;
    i := 0;
    // calculate Digits und sum them up
    while n > 0 do
    begin
      qt := n div base;
      {n mod base}
      sdDigits[i] := n-qt*base;
      inc(sdSumDig,sdDigits[i]);
      n:= qt;
      inc(i);
    end;
    IF sdSumDig  >0 then
      sdIsNiven := (sdNumber MOD sdSumDig = 0);
    sdNivCount := Ord( sdIsNiven);
  end;
  InitSumDigit:=sd;
end;

procedure NextNiven(var sd:tSumDigit);
var
  Num,Sum : tNum;
  i,d,One: NativeUInt;
begin
  One := 1;// put it in a register :-)
  with sd do
  begin
    num := sdNumber;
    Sum := sdSumDig;
    repeat
      //inc sum of digits
      i := 0;
      num += One;
      repeat
        d := sdDigits[i]+One;
        Sum += One;
        //base-1 times the repeat is left here
        if d < base then
        begin
          sdDigits[i] := d;
          BREAK;
        end
        else
        begin
          sdDigits[i] := 0;
          i += One;
          dec(Sum,base);
        end;
      until i > high( sdDigits);
    until (Num MOD Sum) = 0;
    sdIsNiven :=  true;
    sdNumber := num;
    sdSumDig := Sum;
    inc(sdNivCount);
  end;
end;

procedure FindGaps;
var
  delta,LastNiven : TNum;
Begin
  writeln('Gap    Index of gap   Starting Niven');
  writeln('===   =============   ==============');

  LastNiven:= 1;
  MySumDig:=InitSumDigit(LastNiven);
  delta := 0;
  repeat
    NextNiven(MySumDig);
    with MySumDig do
    Begin
      IF delta < sdNumber-LastNiven then
      begin
        delta := sdNumber-LastNiven;
        OutNivenGap(LastNiven,sdNumber,delta);
      end;
      LastNiven:= sdNumber;
    end;
  until MySumDig.sdNumber > 20*1000*1000*1000;
end;

begin
  FindGaps;
end.


use strict;
use warnings;
use List::Util 'sum';

sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }

my ($index, $last, $gap, $count) = (0, 0, 0, 0);
my $threshold = 10_000_000;

print "Gap    Index of gap  Starting Niven\n";
while (1) {
    $count++;
    next unless 0 == $count % sum split //, $count;
    if ((my $diff = $count - $last) > $gap) {
        $gap = $diff;
        printf "%3d %15s %15s\n", $gap, $index > 1 ? comma $index : 1, $last > 1 ? comma $last : 1;
    }
    $last = $count;
    last if ++$index >= $threshold;
}


with javascript_semantics
integer n = 1, prev = 1, g, gap = 0, count = 1, sd = 1
sequence digits={1}

procedure nNiven()
    while 1 do
        n += 1
        for i=length(digits) to 0 by -1 do
            if i=0 then
                digits = prepend(digits,1)
                exit
            end if
            if digits[i]<9 then
                digits[i] += 1
                exit
            end if
            digits[i] = 0
            sd -= 9
        end for
        sd += 1
        if remainder(n,sd)=0 then exit end if
    end while
end procedure

printf(1,"gap size    Niven index      Niven #\n")
atom t0 = time()
while n<=iff(platform()=JS?10_000_000:1_000_000_000) do
    nNiven()
    g = n-prev
    if g>gap then
        string e = elapsed(time()-t0)
        printf(1,"%,5d %,14d %,15d (%s)\n",{g, count, prev, e})
        gap = g
    end if
    prev = n
    count += 1
end while


"""

Python implementation of

http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers

"""

# based on C example

# Returns the sum of the digits of n given the
# sum of the digits of n - 1
def digit_sum(n, sum):
    sum += 1
    while n > 0 and n % 10 == 0:
        sum -= 9
        n /= 10

    return sum

previous = 1
gap = 0
sum = 0
niven_index = 0
gap_index = 1

print("Gap index  Gap    Niven index    Niven number")

niven = 1

while gap_index <= 22:
    sum = digit_sum(niven, sum)
    if niven % sum == 0:
        if niven > previous + gap:
            gap = niven - previous;
            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))
            gap_index += 1
        previous = niven
        niven_index += 1
    niven += 1


use Lingua::EN::Numbers;

unit sub MAIN (Int $threshold = 10000000);

my int $index = 0;
my int $last  = 0;
my int $gap   = 0;

say 'Gap    Index of gap  Starting Niven';

for 1..* -> \count {
    next unless count %% sum count.comb;
    if (my \diff = count - $last) > $gap {
        $gap = diff;
        printf "%3d %15s %15s\n", $gap, comma($index || 1), comma($last || 1);
    }
    ++$index;
    $last = count;
    last if $index >= $threshold;
}


/*REXX program finds and displays the largest gap between  Niven  numbers (up to LIMIT).*/
parse arg lim .                                  /*obtain optional arguments from the CL*/
if lim=='' | lim==','  then lim= 10000000        /*Not specified?  Then use the default.*/
numeric digits 2 + max(8, length(lim) )          /*enable the use of any sized numbers. */
gap= 0;                     old= 0               /*initialize (largest) gap; old Niven #*/
                                              @gsa= 'gap starts at Niven #'
call tell center('gap size', 12)       center(@gsa "index", 29)          center(@gsa, 29)
call tell copies('═'       , 12)       copies('═'         , 29)          copies('═' , 29)
#= 0                                             /*#:  is the index of a Niven number.  */
    do n=1                                       /*◄───── let's go Niven number hunting.*/
    parse var  n  1  sum  2  q                   /*use the first decimal digit for  SUM.*/
                 do  while  q\=='';    parse var q x 2 q;          sum= sum + x
                 end   /*while*/                 /*    ↑                                */
    if n//sum >0  then iterate                   /*    └──────◄ is destructively parsed.*/
    #= # + 1                                     /*bump the  index  of the Niven number.*/
    if n-old<=gap  then do; old= n; iterate; end /*Is gap not bigger?  Then keep looking*/
    gap= n - old;           old= n               /*We found a bigger gap; define new gap*/
    idx= max(1, #-1);       san= max(1, n-gap)   /*handle special case of the first gap.*/
    call tell right(commas(gap),  7)left('', 5), /*center right─justified Niven gap size*/
              right(commas(idx), 25)left('', 4), /*   "     "       "     Niven num idx.*/
              right(commas(san), 25)             /*   "     "       "       "   number. */
    if n >= lim  then leave                      /*have we exceeded the (huge)  LIMit ? */
    end   /*n*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas:  parse arg _;  do c=length(_)-3  to 1  by -3; _=insert(',', _, c); end;   return _
tell:    say arg(1);   return


nivens = Enumerator.new {|y| (1..).each {|n| y << n if n.remainder(n.digits.sum).zero?} }

cur_gap = 0
puts 'Gap    Index of gap  Starting Niven'

nivens.each_cons(2).with_index(1) do |(n1, n2), i|
  break if i > 10_000_000
  if n2-n1 > cur_gap then
    printf "%3d %15s %15s\n", n2-n1, i, n1
    cur_gap = n2-n1
  end
end


// [dependencies]
// num-format = "0.4"

// Returns the sum of the digits of n given the
// sum of the digits of n - 1
fn digit_sum(mut n: u64, mut sum: u64) -> u64 {
    sum += 1;
    while n > 0 && n % 10 == 0 {
        sum -= 9;
        n /= 10;
    }
    sum
}

fn divisible(n: u64, d: u64) -> bool {
    if (d & 1) == 0 && (n & 1) == 1 {
        return false;
    }
    n % d == 0
}

fn main() {
    use num_format::{Locale, ToFormattedString};
    let mut previous = 1;
    let mut gap = 0;
    let mut sum = 0;
    let mut niven_index = 0;
    let mut gap_index = 1;
    let mut niven = 1;
    println!("Gap index  Gap    Niven index    Niven number");
    while gap_index <= 32 {
        sum = digit_sum(niven, sum);
        if divisible(niven, sum) {
            if niven > previous + gap {
                gap = niven - previous;
                println!(
                    "{:9} {:4} {:>14} {:>15}",
                    gap_index,
                    gap,
                    niven_index.to_formatted_string(&Locale::en),
                    previous.to_formatted_string(&Locale::en)
                );
                gap_index += 1;
            }
            previous = niven;
            niven_index += 1;
        }
        niven += 1;
    }
}


import "/fmt" for Fmt

var newSum // recursive
newSum = Fn.new {
    var ms // also recursive
    ms = Fn.new {
        ms = newSum.call()
        return ms.call()
    }
    var msd = 0
    var d = 0
    return Fn.new {
        if (d < 9) {
            d = d + 1
        } else {
            d = 0
            msd = ms.call()
        }
        return msd + d
    }
}

var newHarshard = Fn.new {
    var  i = 0
    var sum = newSum.call()
    return Fn.new {
        i = i + 1
        while (i%sum.call() != 0) i = i + 1
        return i
    }
}

System.print("Gap    Index of gap   Starting Niven")
System.print("===   =============   ==============")
var h = newHarshard.call()
var pg = 0        // previous highest gap
var pn = h.call() // previous Niven number
var i = 1
var n = h.call()
while (n <= 1e9) {
    var g = n - pn
    if (g > pg) {
        System.print("%(Fmt.d(3, g))   %(Fmt.dc(13, i))   %(Fmt.dc(14, pn))")
        pg = g
    }
    pn = n
    i = i + 1
    n = h.call()
}


	bits	64
section	.data
	;;;	Header
header:	db	'Gap no  Gap   Niven index    Niven number',10
	db	'------  ---  -------------  --------------',10
.len:	equ	$-header
	;;;	Placeholder for line output
line:	db	'XXXXXX'
.gapno:	db	'  XXX'
.gap:	db	'  XXXXXXXXXXXXX'
.nivno:	db	'  XXXXXXXXXXXXXX'
.niv:	db	10
.len:	equ 	$-line
section	.text
global	_start
_start:	xor	r8,r8		; Keep a 10 in R8 to divide by
	mov	r8b,10
	mov	rsi,header	; Write header
	mov	rdx,header.len
	call	write
	xor	r15,r15		; Let R15 be the previous number
	inc	r15
	xor	r14,r14		; Let R14 be the gap
	xor	r13,r13		; Let R13 be the digit sum
	xor	r12,r12		; Let R12 be the index
	mov	r11,r15		; Let R11 be the gap index
	xor	r10,r10		; And let R10 be the Niven number
	jmp	niven		; Jump over end of loop
next: 	mov	r15,r10		; Previous number is now current number
	inc	r12		; Increment index
niven:	inc	r10 		; Check next Niven number
	inc	r13		; Calculate next digit sum
	mov	rax,r10		; rax = n/10
	xor	rdx,rdx		; rdx = n%10
digsum:	div	r8
	sub	r13,9		; sum -= 9
	test	rdx,rdx		; was it divisible by 10?
	jnz	check		; if not, we're done
	test	rax,rax		; otherwise, have we reached 0?
	jnz	digsum		; if not, keep going
check:	add	r13,9		; add 9 back
	test	r13b,1		; sum divisible by 2?
	jnz	chdiv		; if not try division
	test	r10b,1		; number divisible by 2?
	jnz	niven
chdiv:	mov	rax,r10		; number divisible by sum?
	xor	rdx,rdx
	div	r13
	test	rdx,rdx
	jnz	niven		; if not, try next number
	mov	rax,r10		; calculate gap size
	sub	rax,r15
	cmp	rax,r14		; bigger than previous gap?
	jbe	next		; If not, count but don't display
	mov	r14,rax		; If so, store new gap size
	mov	rbx,line.niv	; Format Niven number
	mov	rax,r15
	mov	cl,14
	call	format
	dec	rbx
	dec	rbx
	mov	rax,r12		; Niven index
	mov	cl,13
	call	format
	dec	rbx
	dec	rbx
	mov	rax,r14		; Gap
	mov	cl,3
	call 	format
	dec	rbx
	dec 	rbx
	mov	rax,r11		; Gap index
	mov	cl,6
	call	format
	mov	rsi,rbx		; Write line
	mov	rdx,line.len
	call	write
	inc	r11		; Increment gap index
	cmp	r11b,32		; Done?
	jbe	next		; If not, next number
	mov	rax,60
	xor 	rdi,rdi		; Otherwise, exit
	syscall
	;;;	Write RDX chars to STDOUT starting at RSI
write:	xor	rax,rax		; Write syscall is 1
	inc	rax
	mov	rdi,rax		; STDOUT is also 1
	push	r11		; R11 is clobbered, keep it
	syscall
	pop 	r11
	ret
	;;;	Format number in RAX as ASCII, with thousand
	;;;	separators; storing at RBX going leftward,
	;;;	padding with spaces for length CL.
format:	mov	ch,3		; Thousands counter
.loop:	xor	rdx,rdx		; Divide
	div	r8
	add	dl,'0'		; ASCII zero
	dec	rbx		; Store value
	mov	[rbx],dl
	dec	cl		; One fewer char left
	jz	.out		; Stop if field full
	test	rax,rax		; Done whole number?
	jz	.ndone
	dec	ch		; Time for separator?
	jnz	.loop		; If not, continue;
	mov	ch,3		; If so, reset counter,
	dec	rbx		; Add separator,
	mov	[rbx],byte ','
	dec	cl		; One fewer char left
	jmp 	.loop
.ndone:	mov	al,' '		; Pad with spaces
	test	cl,cl		; Done yet?
	jz	.out
.pad:	dec	rbx		; If not, add space
	mov	[rbx],al
	dec	cl
	jnz	.pad
.out:	ret


sub digit_sum(n, sum)
    // devuelve la suma de los dígitos de n dada la suma de los dígitos de n - 1
    sum = sum + 1
    while n > 0 and (mod(n, 10) = 0)
        sum = sum - 9
        n = int(n / 10)
    end while
    return sum
end sub

sub divisible(n, d)
    if mod(d, 1) = 0 and mod(n, 1) = 1 then return 0 else return (mod(n, d) = 0) : endif
end sub

gap_index = 0
previous  = 1
print "Gap index  Gap  Niven index  Niven number"
print "---------  ---  -----------  ------------"

for niven = 1 to 100000000
    sum = digit_sum(niven,sum)
    if divisible(niven, sum) then
        if (niven > previous + gap) then
            gap_index = gap_index + 1
            gap = niven - previous
            print gap_index using "#########";
            print gap using "###";
            print niven_index using "###,###,###";
            print previous using "####,###,###"
        endif
        previous = niven
        niven_index = niven_index + 1
    endif
next niven
end


harshadW:=[1..].tweak(fcn(n){ if(n%(n.split().sum(0))) Void.Skip else n });
harshadW:=Walker.zero().tweak(fcn(go){  // faster than one liner, fewer calls
   foreach h in ([go.value..]){			// spin
      s,t := 0,h; while(t){ s+=t%10; t/=10 }	// sum of digits
      if(0 == h%s){ go.set(h+1); return(h) }
   }
}.fp(Ref(1)));


	org	100h
	jmp	demo
	;;; Increment the number in the $-terminated string under HL.
	;;; The new string is written back to the original location.
	;;; It may grow by one byte (e.g. 999 -> 1000).
incstr:	mvi	a,'$'	; End marker
	lxi	d,303Ah	; D='0', E='9'+1
	lxi	b,0	; Find the end of the string and find the length
isrch:	cmp	m	; Are we there yet?
	inx	b	; If not, try next character
	inx	h
	jnz	isrch
	dcx	h
	dcx	b
	mov	a,b	; Is the string empty?
	ora	c
	rz		; Then return (do nothing)
	inx	b
idigit:	dcx	b	; Go to previous digit
	dcx	h
	mov	a,b	; Are we at the beginning of the string?
	ora	c
	jz	igrow	; Then the string grows (999 -> 1000)
	inr 	m	; Otherwise, increment the digit
	mov	a,e
	cmp	m	; Did we try to increment '9'?
	rnz		; If not, we're done, return
	mov	m,d	; But if so, this digit is now a 0
	jmp	idigit	; And we should do the next digit
igrow:	inx	h
	mvi	m,'1'	; The string should now be '10000...'
	inx	h	; We know the string is at least one char long
	mvi	a,'$'
izero:	cmp 	m	; Are we at the end yet?
	mov	m,d	; In any case, write a zero
	inx	h
	jnz	izero	; If not done, write a zero
	mov	m,a	; Finally, reterminate the string
	ret
	;;;	Demo code: increment the CP/M command line argument
demo:	lxi	h,80h	; $-terminate the string
	mov	a,m
	adi	81h	; Length is at 80h, the argument itself at 81h
	mov	l,a
	mvi	m,'$'
	mvi	l,80h	; Skip any spaces
	mvi	a,' '
space:	inx	h
	cmp	m
	jz 	space
	push	h	; Store the beginning of the string
	call	incstr	; Increment the number in the string
	pop	d	; Print the string
	mvi	c,9
	jmp	5


	cpu	8086
	bits	16
section	.text
	org	100h
	jmp	demo		; Jump towards demo code
	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	;;;	Increment the number in the $-terminated string
	;;;	in [ES:DI]. The string is written back to its original
	;;;	location. It may grow by one byte.
incnum:	mov	al,'$'		; Find string terminator
	mov	bx,di		; Store the beginning of the string
	mov	cx,-1
	repne	scasb
	dec	di		; Move to the terminator
	cmp	bx,di		; If the string is empty, do nothing
	je	.out
.digit:	cmp	bx,di		; Is this the first digit?
	je	.grow		; If so, the string grows
	dec	di		; Go one digit backwards
	inc	byte [es:di]	; Increment the digit
	cmp	byte [es:di],'9'+1	; Did we increment past 9?
	jne	.out		; If not, we're done
	mov	byte [es:di],'0'	; Otherwise, write a zero
	jmp	.digit		; And increment the next digit
.grow:	mov	al,'1'		; Write an 1 first (we know the string
	stosb			; is at least one character long)
	dec	al		; Zero
.zero:	cmp	byte [es:di],'$'	; Are we about to overwrite
	stosb			; the terminator? First, do it anyway;
	jne	.zero		; Keep writing zeroes until $ is reached
	mov	al,'$'		; Finally, write a new terminator
	stosb
.out:	ret
	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	;;;	Demo code: increment the number on the MS-DOS
	;;;	command line.
demo:	mov	si,80h		; $-terminate the string
	lodsb
	xor	bh,bh
	mov	bl,al
	mov	byte [si+bx],'$'
	mov	al,' '		; Skip past any spaces
	mov	cx,-1
	mov	di,si
	repe	scasb
	dec	di
	mov	dx,di		; Keep start of string in DX
	call	incnum		; Increment the number in the string
	mov	ah,9		; Print the string
	int	21h
	ret


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program incstring64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ BUFFERSIZE,   100
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessNum:           .asciz "Enter number : \n"
szCarriageReturn:    .asciz "\n"
szMessResult:        .asciz "Increment number is =  @ \n"      // message result

/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
sBuffer:    .skip BUFFERSIZE
sZoneConv:  .skip 24
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                      // entry of program

    ldr x0,qAdrszMessNum
    bl affichageMess
    mov x0,#STDIN          // Linux input console
    ldr x1,qAdrsBuffer     // buffer address
    mov x2,#BUFFERSIZE     // buffer size
    mov x8, #READ          // request to read datas
    svc 0                  // call system
    ldr x1,qAdrsBuffer     // buffer address
    strb wzr,[x1,x0]       // store zero at the end of input string (x0
    //
    ldr x0,qAdrsBuffer     // buffer address
    bl conversionAtoD      // conversion string in number in x0
                           // increment x0
    add x0,x0,1
                           // conversion register to string
    ldr x1,qAdrsZoneConv
    bl conversion10S       // call conversion
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc  // insert result at @ character
    bl affichageMess       // display message

100:                       // standard end of the program
    mov x0,0               // return code
    mov x8,EXIT            // request to exit program
    svc 0                  // perform the system call

qAdrsZoneConv:          .quad sZoneConv
qAdrszMessNum:          .quad szMessNum
qAdrsBuffer:            .quad sBuffer
qAdrszMessResult:       .quad szMessResult
qAdrszCarriageReturn:   .quad szCarriageReturn
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


report zz_incstring
perform test using: '0', '1', '-1', '10000000', '-10000000'.

form test using iv_string type string.
  data: lv_int  type i,
        lv_string type string.
  lv_int = iv_string + 1.
  lv_string = lv_int.
  concatenate '"' iv_string '" + 1 = "' lv_string '"' into lv_string.
  write / lv_string.
endform.


PROC Increment(CHAR ARRAY src,dst)
  INT val

  val=ValI(src)
  val==+1
  StrI(val,dst)
RETURN

PROC Test(CHAR ARRAY src)
  CHAR ARRAY dst(10)
  Increment(src,dst)
  PrintF("%S+1=%S%E",src,dst)
RETURN

PROC Main()
  Test("0")
  Test("1")
  Test("9999")
  Test("-1")
  Test("-2")
  Test("-10000")
RETURN


function incrementString(str:String):String
{
	return String(Number(str)+1);
}


S : String := "12345";
S := Ada.Strings.Fixed.Trim(Source => Integer'Image(Integer'Value(S) + 1), Side => Ada.Strings.Both);


STRING s := "12345"; FILE f; INT i;
associate(f, s); get(f,i);
i+:=1;
s:=""; reset(f); put(f,i);
print((s, new line))


begin
    % returns a string representing the number in s incremented     %
    % As strings are fixed length, the significant length of s must %
    % be specified in length                                        %
    % s must contain an unsigned integer                            %
    % If the string is invalid or the result would require more     %
    % than 256 characters (the maximum string length), "error"      %
    % is returned                                                   %
    string(256) procedure increment( string(256) value s
                                   ; integer     value length
                                   ) ;
    begin
        logical isValid;
        integer rPos, sPos, carry;
        string(256) iValue;
        string(1) c;
        isValid := true;
        iValue  := " ";
        rPos    := 256;
        sPos    := length - 1;
        carry   := 1; % ensure the first digit is incremented       %
        while isValid and sPos >= 0 and rPos >= 0 do begin
            c      := s( sPos // 1 );
            sPos   := sPos - 1;
            if c not = " " then begin
                isValid := ( c >= "0" and c <= "9" );
                if isValid then begin
                    integer d;
                    d                   := ( decode( c ) - decode( "0" ) ) + carry;
                    carry               := d div 10;
                    rPos                := rPos - 1;
                    iValue( rPos // 1 ) := code( decode( "0" ) + d rem 10 )
                end if_isValid
            end if_c_ne_space
        end while_isValid_and_sPos_ge_0_and_rPOs_ge_0 ;
        if isValid then begin
            % the number was incremented successfully                                     %
            if carry not = 0 then begin
                % need an extra digit                                                     %
                if rPos <= 0
                then isValid := false % no room for an extra digit                        %
                else begin
                    % have space for an extra digit                                       %
                    rPos                := rPos - 1;
                    iValue( rPos // 1 ) := code( decode( "0" ) + carry )
                end if_rPos_lt_0__
            end if_carry_gt_0
        end if_isValid ;
        if not isValid then begin
            % s is not a numeric string or the result would be longer than 256 characters %
            iValue := "error"
            end
        else begin
            % the string could be incremented                                             %
            string(256) rightJustifiedValue;
            rightJustifiedValue := iValue;
            iValue              := " ";
            for iPos := 0 until 255 - rPos do iValue( iPos // 1 ) := rightJustifiedValue( rPos + iPos // 1 )
        end if_not_isValid_or_carry_ne_0__ ;
        iValue
    end increment ;
    % writes the string s, up to the first blank                                          %
    procedure writeonToBlank ( string(256) value s ) ;
    begin
        integer sPos;
        sPos := 0;
        while sPos < 256 and s( sPos // 1 ) not = " " do begin
            writeon( s_w := 0, s( sPos // 1 ) );
            sPos := sPos + 1
        end while_spos_lt_256_and_s_Spos_ne_space
    end writeonToBlank ;
    % test increment                                                                      %
    write( "                   0 + 1: " ); writeonToBlank( increment( "0",                     1 ) );
    write( "                   9 + 1: " ); writeonToBlank( increment( "9",                     1 ) );
    write( "           123456789 + 1: " ); writeonToBlank( increment( "123456789",             9 ) );
    write( "99999999999999999999 + 1: " ); writeonToBlank( increment( "99999999999999999999", 20 ) )
end.


string count = '12345';
count = String.valueOf(integer.valueOf(count)+1);
system.debug('Incremental Value : '+count);


use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

-- succString :: Bool -> String -> String
on succString(blnPruned, s)
    script go
        on |λ|(w)
            try
                if w contains "." then
                    set v to w as real
                else
                    set v to w as integer
                end if
                {(1 + v) as string}
            on error
                if blnPruned then
                    {}
                else
                    {w}
                end if
            end try
        end |λ|
    end script
    unwords(concatMap(go, |words|(s)))
end succString

-- TEST ---------------------------------------------------
on run
    script test
        on |λ|(bln)
            succString(bln, ¬
                "41 pine martens in 1491.3 -1.5 mushrooms ≠ 136")
        end |λ|
    end script
    unlines(map(test, {true, false}))
end run

--> 42 1492.3 -0.5 137
--> 42 pine martens in 1492.3 -0.5 mushrooms ≠ 137

-- GENERIC ------------------------------------------------

-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
    set lng to length of xs
    set acc to {}
    tell mReturn(f)
        repeat with i from 1 to lng
            set acc to acc & |λ|(item i of xs, i, xs)
        end repeat
    end tell
    return acc
end concatMap

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- unlines :: [String] -> String
on unlines(xs)
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, linefeed}
    set str to xs as text
    set my text item delimiters to dlm
    str
end unlines

-- unwords :: [String] -> String
on unwords(xs)
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, space}
    set s to xs as text
    set my text item delimiters to dlm
    return s
end unwords

-- words :: String -> [String]
on |words|(s)
    set ca to current application
    (((ca's NSString's stringWithString:(s))'s ¬
        componentsSeparatedByCharactersInSet:(ca's ¬
            NSCharacterSet's whitespaceAndNewlineCharacterSet()))'s ¬
        filteredArrayUsingPredicate:(ca's ¬
            NSPredicate's predicateWithFormat:"0 < length")) as list
end |words|