with javascript_semantics
enum FPS_UNDEF = 0,
     FPS_CONST,
     FPS_ADD,
     FPS_SUB,
     FPS_MUL,
     FPS_DIV,
     FPS_DERIV,
     FPS_INT,
     FPS_MAX=$

type fps_type(integer f)
    return f>=FPS_UNDEF and f<=FPS_MAX
end type

enum FPS_TYPE, FPS_S1, FPS_S2, FPS_A0
sequence fpss = {}

type fps(object id)
    return integer(id) and id>=1 and id<=length(fpss)
end type

type fpsn(object id)
    return id=NULL or fps(id)
end type

function fps_new(fps_type ft=FPS_UNDEF, fpsn s1=0, s2=0, atom a0=0)
    fpss = append(fpss,{ft,s1,s2,a0})
    fps fpsid = length(fpss)
    return fpsid
end function

-- as per C, for (eg) self or mutually recursive definitions.
procedure fps_redefine(fps fpsid, fps_type ft, fpsn s1id, s2id, object a0="")
    fpss[fpsid][FPS_TYPE] = ft
    fpss[fpsid][FPS_S1] = s1id
    fpss[fpsid][FPS_S2] = s2id
    if atom(a0) then
        fpss[fpsid][FPS_A0] = a0
    end if
end procedure

function fps_const(atom a0)
    fps x = fps_new(FPS_CONST,a0:=a0)
    -- (aside: in the above, the ":=a0" refers to the local namespace
    --         as usual, whereas "a0:=" refers to the param namespace
    --         /inside/ the () of fps_new(), so there is no conflict.)
    return x
end function

constant INF = 1e300*1e300,
         NAN = -(INF/INF)

/* Taking the n-th term of series.  This is where actual work is done. */
function term(fps x, int n)
    atom ret = 0

    {fps_type ft, fpsn s1id, fpsn s2id, atom a0} = fpss[x]
    --  FPS_TYPE,    FPS_S1,    FPS_S2,  FPS_A0 <-- nb above must match
    switch ft do
        case FPS_CONST: ret := iff(n>0 ? 0 : a0)
        case FPS_ADD:   ret := term(s1id, n) + term(s2id, n)
        case FPS_SUB:   ret := term(s1id, n) - term(s2id, n)
        case FPS_MUL:
                for i=0 to n do
                        ret += term(s1id, i) * term(s2id, n-i)
                end for
        case FPS_DIV:
                if not term(s2id, 0) then return NAN end if
                ret = term(s1id, n)
                for i=1 to n do
                        ret -= term(s2id, i) * term(x, n-i) / term(s2id, 0)
                end for
        case FPS_DERIV: ret := n * term(s1id, n+1)
        case FPS_INT:   ret := iff(n=0 ? a0 : term(s1id, n-1)/n)
        default:        ret := 9/0 -- (fatal error)
    end switch
    return ret
end function

procedure term9(string txt, fps x)
    printf(1,"%s:",{txt})
    for i=0 to 9 do printf(1," %g", term(x, i)) end for
    printf(1,"\n")
end procedure

procedure main()
    fps one = fps_const(1)
    fps fcos = fps_new()                    /* cosine */
    fps fsin = fps_new(FPS_INT,fcos)        /* sine */
    fps ftan = fps_new(FPS_DIV,fsin,fcos)   /* tangent */

    /* redefine cos to complete the mutual recursion */
    fps_redefine(fcos, FPS_SUB, one, fps_new(FPS_INT,fsin))

    fps fexp = fps_const(1);        /* exponential */
    /* make exp recurse on self */
    fps_redefine(fexp, FPS_INT, fexp, 0);

    term9("Sin",fsin)
    term9("Cos",fcos)
    term9("Tan",ftan)
    term9("Exp",fexp)
end procedure
main()


(de lazy Args
   (def (car Args)
      (list (cadr Args)
         (cons 'cache (lit (cons))
            (caadr Args)
            (cddr Args) ) ) ) )


''' \
For a discussion on pipe() and head() see
  http://paddy3118.blogspot.com/2009/05/pipe-fitting-with-python-generators.html
'''

from itertools import islice
from fractions import Fraction
from functools import reduce
try:
    from itertools import izip as zip # for 2.6
except:
    pass

def head(n):
    ''' return a generator that passes through at most n items
    '''
    return lambda seq: islice(seq, n)

def pipe(gen, *cmds):
    ''' pipe(a,b,c,d, ...) -> yield from ...d(c(b(a)))
    '''
    return reduce(lambda gen, cmd: cmd(gen), cmds, gen)

def sinepower():
    n = 0
    fac = 1
    sign = +1
    zero = 0
    yield zero
    while True:
        n +=1
        fac *= n
        yield Fraction(1, fac*sign)
        sign = -sign
        n +=1
        fac *= n
        yield zero
def cosinepower():
    n = 0
    fac = 1
    sign = +1
    yield Fraction(1,fac)
    zero = 0
    while True:
        n +=1
        fac *= n
        yield zero
        sign = -sign
        n +=1
        fac *= n
        yield Fraction(1, fac*sign)
def pluspower(*powergenerators):
    for elements in zip(*powergenerators):
        yield sum(elements)
def minuspower(*powergenerators):
    for elements in zip(*powergenerators):
        yield elements[0] - sum(elements[1:])
def mulpower(fgen,ggen):
    'From: http://en.wikipedia.org/wiki/Power_series#Multiplication_and_division'
    a,b = [],[]
    for f,g in zip(fgen, ggen):
        a.append(f)
        b.append(g)
        yield sum(f*g for f,g in zip(a, reversed(b)))
def constpower(n):
    yield n
    while True:
        yield 0
def diffpower(gen):
    'differentiatiate power series'
    next(gen)
    for n, an in enumerate(gen, start=1):
        yield an*n
def intgpower(k=0):
    'integrate power series with constant k'
    def _intgpower(gen):
        yield k
        for n, an in enumerate(gen, start=1):
            yield an * Fraction(1,n)
    return _intgpower

print("cosine")
c = list(pipe(cosinepower(), head(10)))
print(c)
print("sine")
s = list(pipe(sinepower(), head(10)))
print(s)
# integrate cosine
integc = list(pipe(cosinepower(),intgpower(0), head(10)))
# 1 - (integrate sine)
integs1 = list(minuspower(pipe(constpower(1), head(10)),
                          pipe(sinepower(),intgpower(0), head(10))))

assert s == integc, "The integral of cos should be sin"
assert c == integs1, "1 minus the integral of sin should be cos"


#lang lazy

(require racket/match)

;; element-wise addition and subtraction
(define (<+> s1 s2) (map + s1 s2))
(define (<-> s1 s2) (map - s1 s2))

;; element-wise scaling
(define (scale a s) (map (λ (x) (* a x)) s))

;; series multiplication
(define (<*> fs gs)
  (match-let ([(cons f ft) (! fs)]
              [(cons g gt) (! gs)])
    (cons (* f g) (<+> (scale f gt) (<*> ft gs)))))

;; series division
(define (</> fs gs)
  (match-letrec ([(cons f ft) (! fs)]
                 [(cons g gt) (! gs)]
                 [qs (cons (/ f g) (scale (/ g) (<-> ft (<*> qs gt))))])
      qs))

;; integration and differentiation
(define (int f) (map / f (enum 1)))
(define (diff f) (map * (cdr f) (enum 1)))

;; series of natural numbers greater then n
(define (enum n) (cons n (enum (+ 1 n ))))


class DerFPS { ... }
class IntFPS { ... }

role FPS {
    method coeffs        { ... }
    method differentiate { DerFPS.new(:x(self)) }
    method integrate     { IntFPS.new(:x(self)) }

    method pretty($n) {
        sub super($i) { $i.trans('0123456789' => '⁰¹²³⁴⁵⁶⁷⁸⁹') }
        my $str = $.coeffs[0];
        for flat 1..$n Z $.coeffs[1..$n] -> $p, $c {
            when $c > 0 { $str ~= " + { $c .nude.join: '/'}∙x{super($p)}" }
            when $c < 0 { $str ~= " - {-$c .nude.join: '/'}∙x{super($p)}" }
        }
        $str;
    }
}

class ExplicitFPS does FPS { has @.coeffs }

class SumFPS does FPS {
    has FPS ($.x, $.y);
    method coeffs { $.x.coeffs Z+ $.y.coeffs }
}

class DifFPS does FPS {
    has FPS ($.x, $.y);
    method coeffs { $.x.coeffs Z- $.y.coeffs }
}

class ProFPS does FPS {
    has FPS ($.x, $.y);
    method coeffs { (0..*).map: { [+] ($.x.coeffs[0..$_] Z* $.y.coeffs[$_...0]) } }
}

class InvFPS does FPS {
    has FPS $.x;
    method coeffs {
        # see http://en.wikipedia.org/wiki/Formal_power_series#Inverting_series
        flat gather {
            my @a = $.x.coeffs;
            @a[0] != 0 or fail "Cannot invert power series with zero constant term.";
            take my @b = (1 / @a[0]);
            take @b[$_] = -@b[0] * [+] (@a[1..$_] Z* @b[$_-1...0]) for 1..*;
        }
    }
}

class DerFPS does FPS {
    has FPS $.x;
    method coeffs { (1..*).map: { $_ * $.x.coeffs[$_] } }
}

class IntFPS does FPS {
    has FPS $.x;
    method coeffs { 0, |(0..*).map: { $.x.coeffs[$_] / ($_+1) } }
}

class DeferredFPS does FPS {
    has FPS $.realized is rw;
    method coeffs { $.realized.coeffs }
}

# some arithmetic operations for formal power series
multi infix:<+>(FPS $x, FPS $y) { SumFPS.new(:$x, :$y) }
multi infix:<->(FPS $x, FPS $y) { DifFPS.new(:$x, :$y) }
multi infix:<*>(FPS $x, FPS $y) { ProFPS.new(:$x, :$y) }
multi infix:</>(FPS $x, FPS $y) { $x * InvFPS.new(:x($y)) }

# an example of a mixed-type operator:
multi infix:<->(Numeric $x, FPS $y) { ExplicitFPS.new(:coeffs(lazy flat $x, 0 xx *)) - $y }

# define sine and cosine in terms of each other
my $sin       = DeferredFPS.new;
my $cos       = 1 - $sin.integrate;
$sin.realized = $cos.integrate;

# define tangent in terms of sine and cosine
my $tan       = $sin / $cos;

say 'sin(x) ≈ ' ~ $sin.pretty(10);
say 'cos(x) ≈ ' ~ $cos.pretty(10);
say 'tan(x) ≈ ' ~ $tan.pretty(10);


# Class implementing the Formal Power Series type.

class Fps

  # Initialize the FPS instance.
  # When nothing specified, all coefficients are 0.
  # When const: specifies n, all coefficients are n.
  # When delta: specifies n, a[0] = n, then all higher coefficients are zero.
  # When iota: specifies n, coefficients are consecutive integers, beginning with a[0] = n.
  # When init: specifies an array, coefficients are the array elements, padded with zeroes.
  # When enum: specifies a lazy enumerator, that is used for the internal coefficients enum.
  def initialize(const: nil, delta: nil, iota: nil, init: nil, enum: nil)
    # Create (or save) the specified coefficient enumerator.
    case
      when const
        @coeffenum = make_const(const)
      when delta
        @coeffenum = make_delta(delta)
      when iota
        @coeffenum = make_iota(iota)
      when init
        @coeffenum = make_init(init)
      when enum
        @coeffenum = enum
      else
        @coeffenum = make_const(0)
    end
    # Extend the coefficient enumerator instance with an element accessor.
    @coeffenum.instance_eval do
      def [](index)
        self.drop(index).first
      end
    end
  end

  # Return the coefficient at the given index.
  def [](index)
    @coeffenum.drop(index).first
  end

  # Return sum: this FPS plus the given FPS.
  def +(other)
    other = convert(other)
    Fps.new(enum:
      Enumerator.new do |yielder, inx: 0|
        loop do
          yielder.yield(@coeffenum[inx] + other[inx])
          inx += 1
        end
      end.lazy)
  end

  # Return difference: this FPS minus the given FPS.
  def -(other)
    other = convert(other)
    Fps.new(enum:
      Enumerator.new do |yielder, inx: 0|
        loop do
          yielder.yield(@coeffenum[inx] - other[inx])
          inx += 1
        end
      end.lazy)
  end

  # Return product: this FPS multiplied by the given FPS.
  def *(other)
    other = convert(other)
    Fps.new(enum:
      Enumerator.new do |yielder, inx: 0|
        loop do
          coeff = (0..inx).reduce(0) { |sum, i| sum + (@coeffenum[i] * other[inx - i]) }
          yielder.yield(coeff)
          inx += 1
        end
      end.lazy)
  end

  # Return quotient: this FPS divided by the given FPS.
  def /(other)
    other = convert(other)
    Fps.new(enum:
      Enumerator.new do |yielder, inx: 1|
        coeffs = [ Rational(@coeffenum[0], other[0]) ]
        yielder.yield(coeffs[-1])
        loop do
          coeffs <<
            Rational(
              @coeffenum[inx] -
                (1..inx).reduce(0) { |sum, i| sum + (other[i] * coeffs[inx - i]) },
              other[0])
          yielder.yield(coeffs[-1])
          inx += 1
        end
      end.lazy)
  end

  # Return the derivative of this FPS.
  def deriv()
    Fps.new(enum:
      Enumerator.new do |yielder, inx: 0|
        iota = Fps.new(iota: 1)
        loop do
          yielder.yield(@coeffenum[inx + 1] * iota[inx])
          inx += 1
        end
      end.lazy)
  end

  # Return the integral of this FPS.
  def integ()
    Fps.new(enum:
      Enumerator.new do |yielder, inx: 0|
        iota = Fps.new(iota: 1)
        yielder.yield(Rational(0, 1))
        loop do
          yielder.yield(Rational(@coeffenum[inx], iota[inx]))
          inx += 1
        end
      end.lazy)
  end

  # Assign a new value to an existing FPS instance.
  def assign(other)
    other = convert(other)
    @coeffenum = other.get_enum
  end

  # Coerce a Numeric into an FPS instance.
  def coerce(other)
    if other.kind_of?(Numeric)
      [ Fps.new(delta: other), self ]
    else
      raise TypeError 'non-numeric can\'t be coerced into FPS type'
    end
  end

  # Convert to Integer.  (Truncates to 0th coefficient.)
  def to_i()
    @coeffenum[0].to_i
  end

  # Convert to Float.  (Truncates to 0th coefficient.)
  def to_f()
    @coeffenum[0].to_f
  end

  # Convert to Rational.  (Truncates to 0th coefficient.)
  def to_r()
    @coeffenum[0].to_r
  end

  # Convert to String the first count terms of the FPS.
  def to_s(count = 0)
    if count <= 0
      super()
    else
      retstr = ''
      count.times do |inx|
        coeff = (@coeffenum[inx].to_r.denominator == 1) ? @coeffenum[inx].to_i : @coeffenum[inx]
        if !(coeff.zero?)
          prefix = (retstr != '') ? ' ' : ''
          coeffstr =
            ((coeff.abs == 1) && (inx != 0)) ? '' : "#{coeff.abs.to_s}#{(inx == 0) ? '' : '*'}"
          suffix = (inx == 0) ? '' : (inx == 1) ? 'x' : "x^#{inx}"
          if coeff < 0
            prefix << ((retstr != '') ? '- ' : '-')
          else
            prefix << ((retstr != '') ? '+ ' : '')
          end
          retstr << "#{prefix}#{coeffstr}#{suffix}"
        end
      end
      (retstr == '') ? '0' : retstr
    end
  end

  # Evaluate this FPS at the given x value to the given count of terms.
  def eval(x, count)
    @coeffenum.first(count).each_with_index.reduce(0) { |sum, (coeff, inx) | sum + coeff * x**inx }
  end

  # Forward method calls to the @coeffenum instance.
  def method_missing(name, *args, &block)
    @coeffenum.send(name, *args, &block)
  end

  # Forward respond_to? to the @coeffenum instance.
  def respond_to_missing?(name, incl_priv)
    @coeffenum.respond_to?(name, incl_priv)
  end

protected

  # Return reference to the underlying coefficient enumeration.
  def get_enum()
    @coeffenum
  end

private

  # Create a "const" lazy enumerator with the given n.
  # All elements are n.
  def make_const(n)
    Enumerator.new do |yielder|
      loop { yielder.yield(n) }
    end.lazy
  end

  # Create a "delta" lazy enumerator with the given n.
  # First element is n, then all subsequent elements are zero.
  def make_delta(n)
    Enumerator.new do |yielder|
      yielder.yield(n)
      loop { yielder.yield(0) }
    end.lazy
  end

  # Create an "iota" lazy enumerator with the given n.
  # Elements are consecutive integers, beginning with n.
  def make_iota(n)
    Enumerator.new do |yielder, i: n|
      loop { yielder.yield(i); i += 1 }
    end.lazy
  end

  # Create an "init" lazy enumerator with the given array.
  # Elements are the array elements, padded with zeroes.
  def make_init(array)
    Enumerator.new do |yielder, inx: -1|
      loop { yielder.yield((inx < (array.length - 1)) ? array[inx += 1] : 0) }
    end.lazy
  end

  # Convert a Numeric to an FPS instance, if needed.
  def convert(other)
    if other.kind_of?(Fps)
      other
    else
      if other.kind_of?(Numeric)
        Fps.new(delta: other)
      else
        raise TypeError 'non-numeric can\'t be converted to FPS type'
      end
    end
  end

end


(define-syntax lons
  (syntax-rules ()
    ((_ lar ldr) (delay (cons lar (delay ldr))))))

(define (lar lons)
  (car (force lons)))

(define (ldr lons)
  (force (cdr (force lons))))

(define (lap proc . llists)
  (lons (apply proc (map lar llists)) (apply lap proc (map ldr llists))))

(define (take n llist)
  (if (zero? n)
      (list)
      (cons (lar llist) (take (- n 1) (ldr llist)))))

(define (iota n)
  (lons n (iota (+ n 1))))

(define (repeat n)
  (lons n (repeat n)))


package require TclOO

oo::class create PowerSeries {
    variable name
    constructor {{body {}} args} {
        # Use the body to adapt the methods of the _object_
	oo::objdefine [self] $body
        # Use the rest to configure variables in the object
	foreach {var val} $args {
	    set [my varname $var] $val
	}
        # Guess the name if not already set
	if {![info exists [my varname name]]} {
	    set name [namespace tail [self]]
	}
    }
    method name {} {
	return $name
    }
    method term i {
	return 0
    }
    method limit {} {
	return inf
    }

    # A pretty-printer, that prints the first $terms non-zero terms
    method print {terms} {
	set result "${name}(x) == "
	set limit [my limit]
	if {$limit == 0} {
	    # Special case
	    return $result[my term 0]
	}
	set tCount 0
	for {set i 0} {$tCount<$terms && $i<=$limit} {incr i} {
	    set t [my term $i]
	    if {$t == 0} continue
	    incr tCount
	    set t [format %.4g $t]
            if {$t eq "1" && $i != 0} {set t ""}
	    if {$i == 0} {
		append result "$t + "
	    } elseif {$i == 1} {
		append result "${t}x + "
	    } else {
		set p [string map {
		    0 \u2070 1 \u00b9 2 \u00b2 3 \u00b3 4 \u2074
		    5 \u2075 6 \u2076 7 \u2077 8 \u2078 9 \u2079
		} $i]
		append result "${t}x$p + "
	    }
	}
	return [string trimright $result "+ "]
    }

    # Evaluate (a prefix of) the series at a particular x
    # The terms parameter gives the number; 5 is enough for show
    method evaluate {x {terms 5}} {
	set result 0
	set limit [my limit]
	set tCount 0
	for {set i 0} {$tCount<$terms && $i<=$limit} {incr i} {
	    set t [my term $i]
	    if {$t == 0} continue
	    incr tCount
	    set result [expr {$result + $t * ($x ** $i)}]
	}
	return $result
    }

    # Operations to build new sequences from old ones
    method add {s} {
	PowerSeries new {
	    variable S1 S2
	    method limit {} {expr {max([$S1 limit],[$S2 limit])}}
	    method term i {
		set t1 [expr {$i>[$S1 limit] ? 0 : [$S1 term $i]}]
		set t2 [expr {$i>[$S2 limit] ? 0 : [$S2 term $i]}]
		expr {$t1 + $t2}
	    }
	} S1 [self] S2 $s name "$name+[$s name]"
    }
    method subtract {s} {
	PowerSeries new {
	    variable S1 S2
	    method limit {} {expr {max([$S1 limit],[$S2 limit])}}
	    method term i {
		set t1 [expr {$i>[$S1 limit] ? 0 : [$S1 term $i]}]
		set t2 [expr {$i>[$S2 limit] ? 0 : [$S2 term $i]}]
		expr {$t1 - $t2}
	    }
	} S1 [self] S2 $s name "$name-[$s name]"
    }
    method integrate {{Name ""}} {
	if {$Name eq ""} {set Name "Integrate\[[my name]\]"}
	PowerSeries new {
	    variable S limit
	    method limit {} {
		if {[info exists limit]} {return $limit}
		try {
		    return [expr {[$S limit] + 1}]
		} on error {} {
		    # If the limit spirals out of control, it's infinite!
		    return [set limit inf]
		}
	    }
	    method term i {
		if {$i == 0} {return 0}
		set t [$S term [expr {$i-1}]]
		expr {$t / double($i)}
	    }
	} S [self] name $Name
    }
    method differentiate {{Name ""}} {
	if {$Name eq ""} {set Name "Differentiate\[[my name]\]"}
	PowerSeries new {
	    variable S
	    method limit {} {expr {[$S limit] ? [$S limit] - 1 : 0}}
	    method term  i  {expr {[incr i] * [$S term $i]}}
	} S [self] name $Name
    }
    # Special constructor for making constants
    self method constant n {
	PowerSeries new {
	    variable n
	    method limit {} {return 0}
	    method term i {return $n}
	} n $n name $n
    }
}

# Define the two power series in terms of each other
PowerSeries create cos ;# temporary dummy object...
rename [cos integrate "sin"] sin
cos destroy            ;# remove the dummy to make way for the real one...
rename [[PowerSeries constant 1] subtract [sin integrate]] cos


import "/rat" for Rat

class Gene {
    coef(n) {}
}

class Term {
    construct new(gene) {
        _gene = gene
        _cache = []
    }

    gene { _gene }

    [n] {
        if (n < 0) return Rat.zero
        if (n >= _cache.count) {
            for (i in _cache.count..n) _cache.add(gene.coef(i))
        }
        return _cache[n]
    }
}

class FormalPS {
    static DISP_TERM { 12 }
    static X_VAR { "x" }

    construct new() {
        _term = null
    }

    construct new(term) {
        _term = term
    }

    term { _term }

    static fromPolynomial(polynomial) {
        class PolyGene is Gene {
            construct new (polynomial) { _polynomial = polynomial }
            coef(n) { (n < 0 || n >= _polynomial.count) ? Rat.zero : _polynomial[n] }
        }
        return FormalPS.new(Term.new(PolyGene.new(polynomial)))
    }

    copyFrom(other) { _term = other.term }

    inverseCoef(n) {
        var res = List.filled(n+1, null)
        res[0] = _term[0].inverse
        if (n > 0) {
            for (i in 1..n) {
                res[i] = Rat.zero
                for (j in 0...i) res[i] = res[i] + _term[i - j] * res[j]
                res[i] = -res[0] * res[i]
            }
        }
        return res[n]
    }

    +(other) {
        class AddGene is Gene {
            construct new(fps, other) {
                _fps = fps
                _other = other
            }
            coef(n) { _fps.term[n] + _other.term[n] }
        }
        return FormalPS.new(Term.new(AddGene.new(this, other)))
    }

    -(other) {
        class SubGene is Gene {
            construct new(fps, other) {
                _fps = fps
                _other = other
            }
            coef(n) { _fps.term[n] - _other.term[n] }
        }
        return FormalPS.new(Term.new(SubGene.new(this, other)))
    }

    *(other) {
        class MulGene is Gene {
            construct new(fps, other) {
                _fps = fps
                _other = other
            }
            coef(n) {
                var res = Rat.zero
                for (i in 0..n) res = res + _fps.term[i] * _other.term[n-i]
                return res
            }
        }
        return FormalPS.new(Term.new(MulGene.new(this, other)))
    }

    /(other) {
        class DivGene is Gene {
            construct new(fps, other) {
                _fps = fps
                _other = other
            }
            coef(n) {
                var res = Rat.zero
                for (i in 0..n) res = res + _fps.term[i] * _other.inverseCoef(n-i)
                return res
            }
        }
        return FormalPS.new(Term.new(DivGene.new(this, other)))
    }

    diff() {
        class DiffGene is Gene {
            construct new(fps) { _fps = fps }
            coef(n) { _fps.term[n+1] * Rat.new(n+1) }
        }
        return FormalPS.new(Term.new(DiffGene.new(this)))
    }

    intg() {
        class IntgGene is Gene {
            construct new(fps) { _fps= fps }
            coef(n) { (n == 0) ? Rat.zero : _fps.term[n-1] * Rat.new(1, n) }
        }
        return FormalPS.new(Term.new(IntgGene.new(this)))
    }

    toString_(dpTerm) {
        var sb = ""
        var c = _term[0]
        Rat.showAsInt = true
        var supers = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹", "¹⁰", "¹¹"]
        if (c != Rat.zero) sb = sb + c.toString
        for (i in 1...dpTerm) {
            c = term[i]
            if (c != Rat.zero) {
                if (c > Rat.zero && sb.count > 0) sb = sb + " + "
                var xvar = FormalPS.X_VAR
                sb = sb +
                     ((c == Rat.one) ? xvar :
                      (c == Rat.minusOne) ? " - %(xvar)" :
                      (c.num < 0) ? " - %(-c)%(xvar)" : "%(c)%(xvar)")
                if (i > 1) sb = sb + "%(supers[i])"
            }
        }
        if (sb.count == 0) sb = "0"
        sb = sb + " + ..."
        return sb
    }

    toString { toString_(FormalPS.DISP_TERM) }
}

var cos = FormalPS.new()
var sin = cos.intg()
var tan = sin/cos
cos.copyFrom(FormalPS.fromPolynomial([Rat.one]) - sin.intg())
System.print("sin(x)  = %(sin)")
System.print("cos(x)  = %(cos)")
System.print("tan(x)  = %(tan)")
System.print("sin'(x) = %(sin.diff())")
var exp = FormalPS.new()
exp.copyFrom(FormalPS.fromPolynomial([Rat.one]) + exp.intg())
System.print("exp(x)  = %(exp)")


class IPS{
   var [protected] w;   // the coefficients of the infinite series
   fcn init(w_or_a,b,c,etc){  // IPS(1,2,3) --> (1,2,3,0,0,...)
      switch [arglist]{
	 case(Walker)		{ w=w_or_a.tweak(Void,0) }
	 else			{ w=vm.arglist.walker().tweak(Void,0) }
      }
   }
   fcn __opAdd(ipf){   //IPS(1,2,3)+IPS(4,5)-->IPS(5,6,3,0,...), returns modified self
      switch[arglist]{
         case(1){ addConst(ipf) }         // IPS + int/float
	 else   { w=w.zipWith('+,ipf.w) } // IPS + IPS
      }
      self
   }
   fcn __opSub(ipf){ w=w.zipWith('-,ipf.w); self } // IPS - IPSHaskell
   fcn __opMul(ipf){ }  // stub
   fcn __opDiv(x){ w.next().toFloat()/x } // *IPS/x, for integtate()
   fcn __opNegate  { w=w.tweak(Op("--")); self }
   // integtate: b0 = 0 by convention, bn = an-1/n
   fcn integrate{ w=w.zipWith('/,[1..]).push(0.0); self }
   fcn diff     { w=w.zipWith('*,[1..]); 	   self }
   fcn facts{ (1).walker(*).tweak(fcn(n){ (1).reduce(n,'*,1) }) } // 1!,2!...
   fcn walk(n){ w.walk(n) }
   fcn value(x,N=15){ ns:=[1..]; w.reduce(N,'wrap(s,an){ s + an*x.pow(ns.next()) }) }
   fcn cons(k){ w.push(k); self }  //--> k, a0, a1, a2, ...
   // addConst(k) --> k + a0, a1, a2, ..., same as k + IPS
   fcn addConst(k){ (w.next() + k) : w.push(_); self }
}


V n = 10
Int result

L(i) 0 .< n
   I (n % 2) == 0
      L.continue
   I (n % i) == 0
      result = i
      L.break
L.was_no_break
   result = -1
   print(‘No odd factors found’)


         B      TESTPX     goto label TESTPX
         BR     14         goto to the address found in register 14


		JMP $8000		;immediately JuMP to $8000 and begin executing
					;instructions there.


<<Top>>
   Put_Line("Hello, World");
   goto Top;


(
   FOR j TO 1000 DO
     FOR i TO j-1 DO
       IF random > 0.999 THEN
         printf(($"Exited when: i="g(0)", j="g(0)l$,i,j));
         done
       FI
       # etc. #
     OD
   OD;
 done: EMPTY
);


begin
    integer i;
    integer procedure getNumber ;
    begin
        integer n;
        write( "n> " );
        read( i );
        if i< 0 then goto negativeNumber;
        i
    end getNumber ;

    i := getNumber;
    write( "positive or zero" );
    go to endProgram;
negativeNumber:
    writeon( "negative" );
endProgram:
end.


SWI n     ;software system call
B label   ;Branch. Just "B" is a branch always, but any condition code can be added for a conditional branch.
          ;In fact, almost any instruction can be made conditional to avoid branching.

BL label  ;Branch and Link. This is the equivalent of the CALL command on the x86 or Z80.
          ;The program counter is copied to the link register, then the operand of this command becomes the new program counter.

BX Rn     ;Branch and Exchange. The operand is a register. The program counter is swapped with the register specified.
          ;BX LR is commonly used to return from a subroutine.


MsgBox, calling Label1
Gosub, Label1
MsgBox, Label1 subroutine finished
Goto Label2
MsgBox, calling Label2 ; this part is never reached
Return

Label1:
  MsgBox, Label1
Return

Label2:
  MsgBox, Label2 will not return to calling routine
Return


F floyd_warshall(n, edge)
   V rn = 0 .< n
   V dist = rn.map(i -> [1'000'000] * @n)
   V nxt  = rn.map(i -> [0]         * @n)
   L(i) rn
      dist[i][i] = 0
   L(u, v, w) edge
      dist[u - 1][v - 1] = w
      nxt[u - 1][v - 1] = v - 1
   L(k, i, j) cart_product(rn, rn, rn)
      V sum_ik_kj = dist[i][k] + dist[k][j]
      I dist[i][j] > sum_ik_kj
         dist[i][j] = sum_ik_kj
         nxt[i][j] = nxt[i][k]
   print(‘pair      dist     path’)
   L(i, j) cart_product(rn, rn)
      I i != j
         V path = [i]
         L path.last != j
            path.append(nxt[path.last][j])
         print(‘#. -> #.  #4       #.’.format(i + 1, j + 1, dist[i][j], path.map(p -> String(p + 1)).join(‘ -> ’)))

floyd_warshall(4, [(1, 3, -2), (2, 1, 4), (2, 3, 3), (3, 4, 2), (4, 2, -1)])


$ awk 'BEGIN{for(i=1;;i++){if(i%2)continue; if(i>=10)break; print i}}'
2
4
6
8


gosub subrutina

bucle:
print "Bucle infinito"
goto bucle

subrutina:
print "En subrutina"
pause 10
return
end


      GOSUB subroutine

      (loop)
      PRINT "Infinite loop"
      GOTO loop
      END

      (subroutine)
      PRINT "In subroutine"
      WAIT 100
      RETURN


  ( LOOP
  =   out$"Hi again!"
    & !LOOP
  )
& out$Hi!
& !LOOP


*        Floyd-Warshall algorithm - 06/06/2018
FLOYDWAR CSECT
         USING  FLOYDWAR,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         SAVE   (14,12)            save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         MVC    A+8,=F'-2'         a(1,3)=-2
         MVC    A+VV*4,=F'4'       a(2,1)= 4
         MVC    A+VV*4+8,=F'3'     a(2,3)= 3
         MVC    A+VV*8+12,=F'2'    a(3,4)= 2
         MVC    A+VV*12+4,=F'-1'   a(4,2)=-1
         LA     R8,1               k=1
       DO WHILE=(C,R8,LE,V)        do k=1 to v
         LA     R10,A                @a
         LA     R6,1                 i=1
       DO WHILE=(C,R6,LE,V)          do i=1 to v
         LA     R7,1                   j=1
       DO WHILE=(C,R7,LE,V)            do j=1 to v
         LR     R1,R6                    i
         BCTR   R1,0
         MH     R1,=AL2(VV)
         AR     R1,R8                    k
         SLA    R1,2
         L      R9,A-4(R1)               a(i,k)
         LR     R1,R8                    k
         BCTR   R1,0
         MH     R1,=AL2(VV)
         AR     R1,R7                    j
         SLA    R1,2
         L      R3,A-4(R1)               a(k,j)
         AR     R9,R3                    w=a(i,k)+a(k,j)
         L      R2,0(R10)                a(i,j)
       IF CR,R2,GT,R9 THEN               if a(i,j)>w then
         ST     R9,0(R10)                  a(i,j)=w
       ENDIF    ,                        endif
         LA     R10,4(R10)               next @a
         LA     R7,1(R7)                 j++
       ENDDO    ,                      enddo j
         LA     R6,1(R6)               i++
       ENDDO    ,                    enddo i
         LA     R8,1(R8)             k++
       ENDDO    ,                  enddo k
         LA     R10,A              @a
         LA     R6,1               f=1
       DO WHILE=(C,R6,LE,V)        do f=1 to v
         LA     R7,1                 t=1
       DO WHILE=(C,R7,LE,V)          do t=1 to v
       IF CR,R6,NE,R7 THEN             if f^=t then do
         LR     R1,R6                    f
         XDECO  R1,XDEC                  edit f
         MVC    PG+0(4),XDEC+8           output f
         LR     R1,R7                    t
         XDECO  R1,XDEC                  edit t
         MVC    PG+8(4),XDEC+8           output t
         L      R2,0(R10)                a(f,t)
         XDECO  R2,XDEC                  edit a(f,t)
         MVC    PG+12(4),XDEC+8          output a(f,t)
         XPRNT  PG,L'PG                  print
       ENDIF    ,                      endif
         LA     R10,4(R10)             next @a
         LA     R7,1(R7)               t++
       ENDDO    ,                    enddo t
         LA     R6,1(R6)             f++
       ENDDO    ,                  enddo f
         L      R13,4(0,R13)       restore previous savearea pointer
         RETURN (14,12),RC=0       restore registers from calling sav
VV       EQU    4
V        DC     A(VV)
A        DC     (VV*VV)F'99999999' a(vv,vv)
PG       DC     CL80'   . ->    .   .'
XDEC     DS     CL12
         YREGS
         END    FLOYDWAR


--
-- Floyd-Warshall algorithm.
--
-- See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
--

with Ada.Containers.Vectors;
with Ada.Text_IO; use Ada.Text_IO;
with Interfaces;  use Interfaces;

with Ada.Numerics.Generic_Elementary_Functions;

procedure floyd_warshall_task
is
  Floyd_Warshall_Exception : exception;

  -- The floating point type we shall use is one that has infinities.
  subtype FloatPt is IEEE_Float_32;
  package FloatPt_Elementary_Functions is new Ada.Numerics
   .Generic_Elementary_Functions
   (FloatPt);
  use FloatPt_Elementary_Functions;

  -- The following should overflow and give us an IEEE infinity. But I
  -- have kept the code so you could use some non-IEEE floating point
  -- format and set ENORMOUS_FloatPt to some value that is finite but
  -- much larger than actual graph traversal distances.
  ENORMOUS_FloatPt : constant FloatPt :=
   (FloatPt (1.0) / FloatPt (1.0e-37))**1.0e37;

  --
  -- Input is a Vector of records representing the edges of a graph.
  --
  -- Vertices are identified by integers from 1 .. n.
  --

  type edge is record
    u      : Positive;
    weight : FloatPt;
    v      : Positive;
  end record;

  package Edge_Vectors is new Ada.Containers.Vectors
   (Index_Type => Positive, Element_Type => edge);
  use Edge_Vectors;
  subtype edge_vector is Edge_Vectors.Vector;

  --
  -- Floyd-Warshall.
  --

  type distance_array is
   array (Positive range <>, Positive range <>) of FloatPt;

  type next_vertex_array is
   array (Positive range <>, Positive range <>) of Natural;
  Nil_Vertex : constant Natural := 0;

  function find_max_vertex      -- Find the maximum vertex number.
   (edges : in edge_vector)
    return Positive
  is
    max_vertex : Positive;
  begin
    if Is_Empty (edges) then
      raise Floyd_Warshall_Exception with "no edges";
    end if;
    max_vertex := 1;
    for i in edges.First_Index .. edges.Last_Index loop
      max_vertex := Positive'Max (max_vertex, edges.Element (i).u);
      max_vertex := Positive'Max (max_vertex, edges.Element (i).v);
    end loop;
    return max_vertex;
  end find_max_vertex;

  procedure floyd_warshall      -- Perform Floyd-Warshall.
   (edges       : in     edge_vector;
    max_vertex  : in     Positive;
    distance    :    out distance_array;
    next_vertex :    out next_vertex_array)
  is
    u, v     : Positive;
    dist_ikj : FloatPt;
  begin

    -- Initialize.

    for i in 1 .. max_vertex loop
      for j in 1 .. max_vertex loop
        distance (i, j)    := ENORMOUS_FloatPt;
        next_vertex (i, j) := Nil_Vertex;
      end loop;
    end loop;
    for i in edges.First_Index .. edges.Last_Index loop
      u                  := edges.Element (i).u;
      v                  := edges.Element (i).v;
      distance (u, v)    := edges.Element (i).weight;
      next_vertex (u, v) := v;
    end loop;
    for i in 1 .. max_vertex loop
      distance (i, i) :=
       FloatPt (0.0);           -- Distance from a vertex to itself.
      next_vertex (i, i) := i;
    end loop;

    -- Perform the algorithm.

    for k in 1 .. max_vertex loop
      for i in 1 .. max_vertex loop
        for j in 1 .. max_vertex loop
          dist_ikj := distance (i, k) + distance (k, j);
          if dist_ikj < distance (i, j) then
            distance (i, j)    := dist_ikj;
            next_vertex (i, j) := next_vertex (i, k);
          end if;
        end loop;
      end loop;
    end loop;

  end floyd_warshall;

  --
  -- Path reconstruction.
  --

  procedure put_path
   (next_vertex : in next_vertex_array;
    u, v        : in Positive)
  is
    i : Positive;
  begin
    if next_vertex (u, v) /= Nil_Vertex then
      i := u;
      Put (Positive'Image (i));
      while i /= v loop
        Put (" ->");
        i := next_vertex (i, v);
        Put (Positive'Image (i));
      end loop;
    end if;
  end put_path;

  example_graph : edge_vector;
  max_vertex    : Positive;

begin
  Append (example_graph, (u => 1, weight => FloatPt (-2.0), v => 3));
  Append (example_graph, (u => 3, weight => FloatPt (+2.0), v => 4));
  Append (example_graph, (u => 4, weight => FloatPt (-1.0), v => 2));
  Append (example_graph, (u => 2, weight => FloatPt (+4.0), v => 1));
  Append (example_graph, (u => 2, weight => FloatPt (+3.0), v => 3));

  max_vertex := find_max_vertex (example_graph);

  declare

    distance    : distance_array (1 .. max_vertex, 1 .. max_vertex);
    next_vertex : next_vertex_array
     (1 .. max_vertex, 1 .. max_vertex);

  begin

    floyd_warshall (example_graph, max_vertex, distance, next_vertex);

    Put_Line ("  pair       distance        path");
    Put_Line ("---------------------------------------------");
    for u in 1 .. max_vertex loop
      for v in 1 .. max_vertex loop
        if u /= v then
          Put (Positive'Image (u));
          Put (" ->");
          Put (Positive'Image (v));
          Put ("    ");
          Put (FloatPt'Image (distance (u, v)));
          Put ("    ");
          put_path (next_vertex, u, v);
          Put_Line ("");
        end if;
      end loop;
    end loop;

  end;
end floyd_warshall_task;


int main()
{
  int i,j;
  for (j=1; j<1000; j++) {
    for (i=0; i<j, i++) {
      if (exit_early())
        goto out;
      /* etc. */
    }
  }
out:
  return 0;
}


#include <iostream>

int main()
{
 LOOP:
  std::cout << "Hello, World!\n";
 goto LOOP;
}


       PROGRAM-ID. Go-To-Example.

       PROCEDURE DIVISION.
       Foo.
           DISPLAY "Just a reminder: GO TOs are evil."

           GO TO Foo
           .


(*
  Floyd-Warshall algorithm.

  See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
*)

#include "share/atspre_staload.hats"

#define NIL list_nil ()
#define :: list_cons

typedef Pos = [i : pos] int i

(*------------------------------------------------------------------*)

(* Square arrays with 1-based indexing. *)

extern praxi
lemma_square_array_indices {n    : pos}
                           {i, j : pos | i <= n; j <= n}
                           () :<prf>
  [0 <= (i - 1) + ((j - 1) * n);
   (i - 1) + ((j - 1) * n) < n * n]
  void

typedef square_array (t : [email protected]+, n : int) =
  '{
    side_length = int n,
    elements = arrayref (t, n * n)
  }

fn {t : [email protected]}
make_square_array {n    : nat}
                  (n    : int n,
                   fill : t) : square_array (t, n) =
  let
    prval () = mul_gte_gte_gte {n, n} ()
  in
    '{
      side_length = n,
      elements = arrayref_make_elt (i2sz (n * n), fill)
    }
  end

fn {t : [email protected]}
square_array_get_at {n    : pos}
                    {i, j : pos | i <= n; j <= n}
                    (arr  : square_array (t, n),
                     i    : int i,
                     j    : int j) : t =
  let
    prval () = lemma_square_array_indices {n} {i, j} ()
  in
    arrayref_get_at (arr.elements,
                     (i - 1) + ((j - 1) * arr.side_length))
  end

fn {t : [email protected]}
square_array_set_at {n    : pos}
                    {i, j : pos | i <= n; j <= n}
                    (arr  : square_array (t, n),
                     i    : int i,
                     j    : int j,
                     x    : t) : void =
  let
    prval () = lemma_square_array_indices {n} {i, j} ()
  in
    arrayref_set_at (arr.elements,
                     (i - 1) + ((j - 1) * arr.side_length),
                     x)
  end

overload [] with square_array_get_at
overload [] with square_array_set_at

(*------------------------------------------------------------------*)

typedef floatpt = float
extern castfn i2floatpt : int -<> floatpt
macdef arbitrary_floatpt = i2floatpt (12345)

typedef distance_array (n : int) = square_array (floatpt, n)

typedef vertex = [i : nat] int i
#define NIL_VERTEX 0
typedef next_vertex_array (n : int) = square_array (vertex, n)

typedef edge =
  '{      (* The ' means this is allocated by the garbage collector.*)
    u = vertex,
    weight = floatpt,
    v = vertex
  }
typedef edge_list (n : int) = list (edge, n)
typedef edge_list = [n : int] edge_list (n)

prfn                           (* edge_list have non-negative size. *)
lemma_edge_list_param {n : int} (edges : edge_list n)
    :<prf> [0 <= n] void =
  lemma_list_param edges

(*------------------------------------------------------------------*)

fn
find_max_vertex (edges : edge_list) : vertex =
  let
    fun
    loop {n : nat} .<n>.
         (p : edge_list n,
          u : vertex) : vertex =
      case+ p of
      | NIL => u
      | head :: tail =>
        loop (tail, max (max (u, (head.u)), (head.v)))

    prval () = lemma_edge_list_param edges
  in
    assertloc (isneqz edges);
    loop (edges, 0)
  end

fn
floyd_warshall {n           : int}
               (edges       : edge_list,
                n           : int n,
                distance    : distance_array n,
                next_vertex : next_vertex_array n) : void =
  let
    val () = assertloc (1 <= n)
  in

    (* This implementation does NOT initialize (to any meaningful
       value) elements of "distance" that would be set "infinite" in
       the Wikipedia pseudocode. Instead you should use the
       "next_vertex" array to determine whether there exists a finite
       path from one vertex to another.

       Thus we avoid any dependence on IEEE floating point or on the
       settings of the FPU. *)

    (* Initialize. *)

    let
      var i : Pos
    in
      for (i := 1; i <= n; i := succ i)
        let
          var j : Pos
        in
          for (j := 1; j <= n; j := succ j)
            next_vertex[i, j] := NIL_VERTEX
        end
    end;
    let
      var p : edge_list
    in
      for (p := edges; list_is_cons p; p := list_tail p)
        let
          val head = list_head p
          val u = head.u
          val () = assertloc (u <> NIL_VERTEX)
          val () = assertloc (u <= n)
          val v = head.v
          val () = assertloc (v <> NIL_VERTEX)
          val () = assertloc (v <= n)
        in
          distance[u, v] := head.weight;
          next_vertex[u, v] := v
        end
    end;
    let
      var i : Pos
    in
      for (i := 1; i <= n; i := succ i)
        begin
          (* Distance from a vertex to itself is zero. *)
          distance[i, i] := i2floatpt (0);
          next_vertex[i, i] := i
        end
    end;

    (* Perform the algorithm. *)

    let
      var k : Pos
    in
      for (k := 1; k <= n; k := succ k)
        let
          var i : Pos
        in
          for (i := 1; i <= n; i := succ i)
            let
              var j : Pos
            in
              for (j := 1; j <= n; j := succ j)
                if next_vertex[i, k] <> NIL_VERTEX
                      && next_vertex[k, j] <> NIL_VERTEX then
                  let
                    val dist_ikj = distance[i, k] + distance[k, j]
                  in
                    if next_vertex[i, j] = NIL_VERTEX
                          || dist_ikj < distance[i, j] then
                      begin
                        distance[i, j] := dist_ikj;
                        next_vertex[i, j] := next_vertex[i, k]
                      end
                  end
            end
        end
    end

  end

fn
print_path {n           : int}
           (n           : int n,
            next_vertex : next_vertex_array n,
            u           : Pos,
            v           : Pos) : void =
  if 0 < n then
    let
      val () = assertloc (u <= n)
      val () = assertloc (v <= n)
    in
      if next_vertex[u, v] <> NIL_VERTEX then
        let
          var i : Int
        in
          i := u;
          print! (i);
          while (i <> v)
            let
              val () = assertloc (1 <= i)
              val () = assertloc (i <= n)
            in
              print! (" -> ");
              i := next_vertex[i, v];
              print! (i)
            end
        end
    end

implement
main0 () =
  let

    (* One might notice that (because consing prepends rather than
       appends) the order of edges here is *opposite* to that of some
       other languages' implementations. But the order of the edges is
       immaterial. *)
    val example_graph = NIL
    val example_graph =
      '{u = 1, weight = i2floatpt (~2), v = 3} :: example_graph
    val example_graph =
      '{u = 3, weight = i2floatpt (2), v = 4} :: example_graph
    val example_graph =
      '{u = 4, weight = i2floatpt (~1), v = 2} :: example_graph
    val example_graph =
      '{u = 2, weight = i2floatpt (4), v = 1} :: example_graph
    val example_graph =
      '{u = 2, weight = i2floatpt (3), v = 3} :: example_graph

    val n = find_max_vertex (example_graph)
    val distance = make_square_array<floatpt> (n, arbitrary_floatpt)
    val next_vertex = make_square_array<vertex> (n, NIL_VERTEX)

  in

    floyd_warshall (example_graph, n, distance, next_vertex);

    println! ("  pair      distance      path");
    println! ("------------------------------------------");
    let
      var u : Pos
    in
      for (u := 1; u <= n; u := succ u)
        let
          var v : Pos
        in
          for (v := 1; v <= n; v := succ v)
            if u <> v then
              begin
                print! (" ", u, " -> ", v, "    ");
                if i2floatpt (0) <= distance[u, v] then
                  print! (" ");
                print! (distance[u, v], "     ");
                print_path (n, next_vertex, u, v);
                println! ()
              end
        end
    end

  end


#include<limits.h>
#include<stdlib.h>
#include<stdio.h>

typedef struct{
    int sourceVertex, destVertex;
    int edgeWeight;
}edge;

typedef struct{
    int vertices, edges;
    edge* edgeMatrix;
}graph;

graph loadGraph(char* fileName){
    FILE* fp = fopen(fileName,"r");

    graph G;
    int i;

    fscanf(fp,"%d%d",&G.vertices,&G.edges);

    G.edgeMatrix = (edge*)malloc(G.edges*sizeof(edge));

    for(i=0;i<G.edges;i++)
        fscanf(fp,"%d%d%d",&G.edgeMatrix[i].sourceVertex,&G.edgeMatrix[i].destVertex,&G.edgeMatrix[i].edgeWeight);

    fclose(fp);

    return G;
}

void floydWarshall(graph g){
    int processWeights[g.vertices][g.vertices], processedVertices[g.vertices][g.vertices];
    int i,j,k;

    for(i=0;i<g.vertices;i++)
        for(j=0;j<g.vertices;j++){
            processWeights[i][j] = SHRT_MAX;
            processedVertices[i][j] = (i!=j)?j+1:0;
        }

    for(i=0;i<g.edges;i++)
        processWeights[g.edgeMatrix[i].sourceVertex-1][g.edgeMatrix[i].destVertex-1] = g.edgeMatrix[i].edgeWeight;

    for(i=0;i<g.vertices;i++)
        for(j=0;j<g.vertices;j++)
            for(k=0;k<g.vertices;k++){
                if(processWeights[j][i] + processWeights[i][k] < processWeights[j][k]){
                    processWeights[j][k] = processWeights[j][i] + processWeights[i][k];
                    processedVertices[j][k] = processedVertices[j][i];
                }
            }

    printf("pair    dist   path");
    for(i=0;i<g.vertices;i++)
        for(j=0;j<g.vertices;j++){
            if(i!=j){
                printf("\n%d -> %d %3d %5d",i+1,j+1,processWeights[i][j],i+1);
                k = i+1;
                do{
                    k = processedVertices[k-1][j];
                    printf("->%d",k);
                }while(k!=j+1);
            }
        }
}

int main(int argC,char* argV[]){
    if(argC!=2)
        printf("Usage : %s <file containing graph data>");
    else
        floydWarshall(loadGraph(argV[1]));
    return 0;
}


myprocedure
END // End of main program
PROC myprocedure
PRINT "Hello, this is a procedure"
ENDPROC myprocedure


import std.stdio;

void main() {
    label1:
    writeln("I'm in your infinite loop.");
    goto label1;
}


: checked-array
  CREATE ( size -- ) DUP , CELLS ALLOT
  DOES> ( i -- a+i )
    2DUP @ 0 SWAP WITHIN IF
      SWAP 1+ CELLS +
    ELSE
      1 THROW
    THEN ;

8 checked-array myarray

: safe-access ( i -- a[i] )
  ['] myarray CATCH 1 = IF ." Out of bounds!" 0 THEN ;


using System;

namespace FloydWarshallAlgorithm {
    class Program {
        static void FloydWarshall(int[,] weights, int numVerticies) {
            double[,] dist = new double[numVerticies, numVerticies];
            for (int i = 0; i < numVerticies; i++) {
                for (int j = 0; j < numVerticies; j++) {
                    dist[i, j] = double.PositiveInfinity;
                }
            }

            for (int i = 0; i < weights.GetLength(0); i++) {
                dist[weights[i, 0] - 1, weights[i, 1] - 1] = weights[i, 2];
            }

            int[,] next = new int[numVerticies, numVerticies];
            for (int i = 0; i < numVerticies; i++) {
                for (int j = 0; j < numVerticies; j++) {
                    if (i != j) {
                        next[i, j] = j + 1;
                    }
                }
            }

            for (int k = 0; k < numVerticies; k++) {
                for (int i = 0; i < numVerticies; i++) {
                    for (int j = 0; j < numVerticies; j++) {
                        if (dist[i, k] + dist[k, j] < dist[i, j]) {
                            dist[i, j] = dist[i, k] + dist[k, j];
                            next[i, j] = next[i, k];
                        }
                    }
                }
            }

            PrintResult(dist, next);
        }

        static void PrintResult(double[,] dist, int[,] next) {
            Console.WriteLine("pair     dist    path");
            for (int i = 0; i < next.GetLength(0); i++) {
                for (int j = 0; j < next.GetLength(1); j++) {
                    if (i != j) {
                        int u = i + 1;
                        int v = j + 1;
                        string path = string.Format("{0} -> {1}    {2,2:G}     {3}", u, v, dist[i, j], u);
                        do {
                            u = next[u - 1, v - 1];
                            path += " -> " + u;
                        } while (u != v);
                        Console.WriteLine(path);
                    }
                }
            }
        }

        static void Main(string[] args) {
            int[,] weights = { { 1, 3, -2 }, { 2, 1, 4 }, { 2, 3, 3 }, { 3, 4, 2 }, { 4, 2, -1 } };
            int numVerticies = 4;

            FloydWarshall(weights, numVerticies);
        }
    }
}


      ...
      ASSIGN 1101 to WHENCE   !Remember my return point.
      GO TO 1000              !Dive into a "subroutine"
 1101 CONTINUE                !Resume.
      ...
      ASSIGN 1102 to WHENCE   !Prepare for another invocation.
      GO TO 1000              !Like GOSUB in BASIC.
 1102 CONTINUE                !Carry on.
      ...
Common code, far away.
 1000 do something            !This has all the context available.
      GO TO WHENCE            !Return whence I came.


'$lang: "qb"

Gosub subrutina

bucle:
Print "Bucle infinito"
Goto bucle
End

subrutina:
Print "En subrutina"
Sleep 100
Return
Sleep


Public Sub Main()
Dim siCount As Short

LOOPIT:

Print siCount;;
Inc siCount
If siCount > 100 Then Quit
Goto LoopIt

End


#include <iostream>
#include <vector>
#include <sstream>

void print(std::vector<std::vector<double>> dist, std::vector<std::vector<int>> next) {
  std::cout << "(pair, dist, path)" << std::endl;
  const auto size = std::size(next);
  for (auto i = 0; i < size; ++i) {
    for (auto j = 0; j < size; ++j) {
      if (i != j) {
        auto u = i + 1;
        auto v = j + 1;
        std::cout << "(" << u << " -> " << v << ", " << dist[i][j]
          << ", ";
        std::stringstream path;
        path << u;
        do {
          u = next[u - 1][v - 1];
          path << " -> " << u;
        } while (u != v);
        std::cout << path.str() << ")" << std::endl;
      }
    }
  }
}

void solve(std::vector<std::vector<int>> w_s, const int num_vertices) {
  std::vector<std::vector<double>> dist(num_vertices);
  for (auto& dim : dist) {
    for (auto i = 0; i < num_vertices; ++i) {
      dim.push_back(INT_MAX);
    }
  }
  for (auto& w : w_s) {
    dist[w[0] - 1][w[1] - 1] = w[2];
  }
  std::vector<std::vector<int>> next(num_vertices);
  for (auto i = 0; i < num_vertices; ++i) {
    for (auto j = 0; j < num_vertices; ++j) {
      next[i].push_back(0);
    }
    for (auto j = 0; j < num_vertices; ++j) {
      if (i != j) {
        next[i][j] = j + 1;
      }
    }
  }
  for (auto k = 0; k < num_vertices; ++k) {
    for (auto i = 0; i < num_vertices; ++i) {
      for (auto j = 0; j < num_vertices; ++j) {
        if (dist[i][j] > dist[i][k] + dist[k][j]) {
          dist[i][j] = dist[i][k] + dist[k][j];
          next[i][j] = next[i][k];
        }
      }
    }
  }
  print(dist, next);
}

int main() {
  std::vector<std::vector<int>> w = {
    { 1, 3, -2 },
    { 2, 1, 4 },
    { 2, 3, 3 },
    { 3, 4, 2 },
    { 4, 2, -1 },
  };
  int num_vertices = 4;
  solve(w, num_vertices);
  std::cin.ignore();
  std::cin.get();
  return 0;
}


10 LET a=1
20 IF a=2 THEN PRINT "This is a conditional statement"
30 IF a=1 THEN GOTO 50: REM a conditional jump
40 PRINT "This statement will be skipped"
50 PRINT ("Hello" AND (1=2)): REM This does NOT PRINT
100 PRINT "Endless loop"
110 GOTO 100:REM an unconditional jump


import Control.Monad
import Control.Monad.Trans
import Control.Monad.Exit

main = do
    runExitTMaybe $ do
        forM_ [1..5] $ \x -> do
            forM_ [1..5] $ \y -> do
                lift $ print (x, y)
                when (x == 3 && y == 2) $
                    exitWith ()
    putStrLn "Done."


1 GOTO 2 ! branch to label

2 READ(FIle=name, IOStat=ios, ERror=3) something ! on error branch to label 3

3 ALARM(delay, n) ! n=2...9 simulate F2 to F9 keys: call asynchronously "Alarm"-SUBROUTINES F2...F9 with a delay

4 ALARM(  1  ) ! lets HicEst wait at this statement for any keyboard or mouse event

5 SYSTEM(WAIT=1000) ! msec

6 XEQ('CALL my_subroutine', *7) ! executes command string, on error branch to label 7

7 y = EXP(1E100, *8) ! on error branch to label 8

8 y = LOG( 0 , *9)   ! on error branch to label 9

9 ALARM( 999 ) ! quit HicEst immediately


#!/bin/sh
#|-*- mode:lisp -*-|#
#|
exec ros -Q -- $0 "[email protected]"
|#
(progn ;;init forms
  (ros:ensure-asdf)
  #+quicklisp(ql:quickload '() :silent t)
  )

(defpackage :ros.script.floyd-warshall.3861181636
  (:use :cl))
(in-package :ros.script.floyd-warshall.3861181636)

;;;
;;; Floyd-Warshall algorithm.
;;;
;;; See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
;;;
;;; Translated from the Scheme. Small improvements (or what might be
;;; considered improvements), and some type specialization, have been
;;; added.
;;;

;;;-------------------------------------------------------------------
;;;
;;; A square array will be represented by an ordinary Common Lisp
;;; array, but accessed through our own functions (which look similar
;;; to, although not identical to, the corresponding Scheme
;;; functions).
;;;
;;; Square arrays are indexed *starting at one*.
;;;

(defun make-arr (n &key (element-type t) initial-element)
  (make-array (list n n) :element-type element-type
                         :initial-element initial-element))

(defun arr-set (arr i j x)
  (setf (aref arr (- i 1) (- j 1)) x))

(defun arr-ref (arr i j)
  (aref arr (- i 1) (- j 1)))

;;;-------------------------------------------------------------------
;;;
;;; Floyd-Warshall.
;;;
;;; Input is a list of length-3 lists representing edges; each entry
;;; is:
;;;
;;;    (start-vertex edge-weight end-vertex)
;;;
;;; where vertex identifiers are integers from 1 .. n.
;;;
;;; A difference from the Scheme implementation is that here we do not
;;; assume the floating point supports "infinities". In the Scheme we
;;; did, because in R7RS small there is support for such infinities
;;; (although the standard does not *require* them). Also because
;;; alternatives were not yet apparent to this author. :)
;;;

(defvar *floatpt* 'single-float)
(defconstant nil-vertex 0)

(defun floyd-warshall (edges)
  (let* ((n
           ;; Set n to the maximum vertex number. By design, n also
           ;; equals the number of vertices.
           (max (apply #'max (mapcar #'car edges))
                (apply #'max (mapcar #'caddr edges))))

         (distance
           ;; The distances are initialized to a purely arbitrary
           ;; value. An entry in the "distance" array is meaningful
           ;; *only* if the corresponding entry in "next-vertex" is
           ;; not the nil-vertex.
           (make-arr n :element-type *floatpt*
                       :initial-element (coerce 12345 *floatpt*)))

         (next-vertex
           ;; Unless later set otherwise, an entry in "next-vertex"
           ;; will be the nil-vertex.
           (make-arr n :element-type 'fixnum
                       :initial-element nil-vertex)))

    (defun dist (p q) (arr-ref distance p q))
    (defun next (p q) (arr-ref next-vertex p q))

    (defun set-dist (p q x) (arr-set distance p q x))
    (defun set-next (p q x) (arr-set next-vertex p q x))

    (defun nilnext (p q) (= (next p q) nil-vertex))

    ;; Initialize "distance" and "next-vertex".
    (loop for edge in edges
          do (let ((u (car edge))
                   (weight (cadr edge))
                   (v (caddr edge)))
               (set-dist u v weight)
               (set-next u v v)))
    (loop for v from 1 to n
          do (progn
               ;; The distance from a vertex to itself = 0.0.
               (set-dist v v (coerce 0 *floatpt*))
               (set-next v v v)))

    ;; Perform the algorithm.
    (loop
      for k from 1 to n
      do (loop
           for i from 1 to n
           do (loop
                for j from 1 to n
                do (and (not (nilnext i k))
                        (not (nilnext k j))
                        (let* ((dist-ikj (+ (dist i k) (dist k j))))
                          (when (or (nilnext i j)
                                    (< dist-ikj (dist i j)))
                            (set-dist i j dist-ikj)
                            (set-next i j (next i k))))))))

    ;; Return the results.
    (values n distance next-vertex)))

;;;-------------------------------------------------------------------
;;;
;;; Path reconstruction from the "next-vertex" array.
;;;
;;; The return value is a list of vertices.
;;;

(defun find-path (next-vertex u v)
  (if (= (arr-ref next-vertex u v) nil-vertex)
      (list)
      (cons u (let ((i u))
                (loop while (/= i v)
                      do (setf i (arr-ref next-vertex i v))
                      collect i)))))

;;;-------------------------------------------------------------------

(defun directed-vertex-list-to-string (lst)
  (if (not lst)
      ""
      (let ((s (write-to-string (car lst))))
        (loop for u in (cdr lst)
              do (setf s (concatenate 'string s " -> "
                                      (write-to-string u))))
        s)))

;;;-------------------------------------------------------------------

(defun main (&rest argv)
  (declare (ignorable argv))
  (let ((example-graph
          (mapcar (lambda (x) (list (coerce (car x) 'fixnum)
                                    (coerce (cadr x) *floatpt*)
                                    (coerce (caddr x) 'fixnum)))
                  '((1 -2 3)
                    (3 2 4)
                    (4 -1 2)
                    (2 4 1)
                    (2 3 3)))))
    (multiple-value-bind (n distance next-vertex)
        (floyd-warshall example-graph)
      (princ "  pair    distance   path")
      (terpri)
      (princ "-------------------------------------")
      (terpri)
      (loop
        for u from 1 to n
        do (loop
             for v from 1 to n
             do (unless (= u v)
                  (format
                   t " ~A [email protected]     ~A~%"
                   (directed-vertex-list-to-string (list u v))
                   (if (= (arr-ref next-vertex u v) nil-vertex)
                       "   no path"
                       (write-to-string (arr-ref distance u v)))
                   (directed-vertex-list-to-string
                    (find-path next-vertex u v)))))))))

;;;-------------------------------------------------------------------
;;; vim: set ft=lisp lisp:


    if x := every i := 1 to *container do {     # * is the 'length' operator
        if container[i] ~== y then
            write("item ", i, " is not interesting")
        else
            break a
    } then
        write("found item ", x)
    else
        write("did not find an item")


switch (xx) {
  case 1:
  case 2:
    /* 1 & 2 both come here... */
    ...
    break;
  case 4:
    /* 4 comes here... */
    ...
    break;
  case 5:
    /* 5 comes here... */
    ...
    break;
  default:
    /* everything else */
    break;
}

for (int i = 0; i < 10; ++i) {
  ...
  if (some_condition) { break; }
  ...
}

_Time_: do {
  for (int i = 0; i < 10; ++i) {
    ...
    if (some_condition) { break _Time_; /* terminate the do-while loop */}
    ...
    }
  ...
} while (thisCondition);


import std.stdio;

void main() {
    int[][] weights = [
        [1, 3, -2],
        [2, 1, 4],
        [2, 3, 3],
        [3, 4, 2],
        [4, 2, -1]
    ];
    int numVertices = 4;

    floydWarshall(weights, numVertices);
}

void floydWarshall(int[][] weights, int numVertices) {
    import std.array;

    real[][] dist = uninitializedArray!(real[][])(numVertices, numVertices);
    foreach(dim; dist) {
        dim[] = real.infinity;
    }

    foreach (w; weights) {
        dist[w[0]-1][w[1]-1] = w[2];
    }

    int[][] next = uninitializedArray!(int[][])(numVertices, numVertices);
    for (int i=0; i<next.length; i++) {
        for (int j=0; j<next.length; j++) {
            if (i != j) {
                next[i][j] = j+1;
            }
        }
    }

    for (int k=0; k<numVertices; k++) {
        for (int i=0; i<numVertices; i++) {
            for (int j=0; j<numVertices; j++) {
                if (dist[i][j] > dist[i][k] + dist[k][j]) {
                    dist[i][j] = dist[i][k] + dist[k][j];
                    next[i][j] = next[i][k];
                }
            }
        }
    }

    printResult(dist, next);
}

void printResult(real[][] dist, int[][] next) {
    import std.conv;
    import std.format;

    writeln("pair     dist    path");
    for (int i=0; i<next.length; i++) {
        for (int j=0; j<next.length; j++) {
            if (i!=j) {
                int u = i+1;
                int v = j+1;
                string path = format("%d -> %d    %2d     %s", u, v, cast(int) dist[i][j], u);
                do {
                    u = next[u-1][v-1];
                    path ~= text(" -> ", u);
                } while (u != v);
                writeln(path);
            }
        }
    }
}


$ jq -n '1, (2 | label $foo | debug | 3 | break $foo | debug), 4'
1
["DEBUG:",2]
4


function example()
    println("Hello ")
    @goto world
    println("Never printed")
    @label world
    println("world")
end


// version 1.0.6

fun main(args: Array<String>) {
    for (i in 0 .. 2) {
        for (j in 0 .. 2) {
            if (i + j == 2) continue
            if (i + j == 3) break
            println(i + j)
        }
    }
    println()
    if (args.isNotEmpty()) throw IllegalArgumentException("No command line arguments should be supplied")
    println("Goodbye!")  // won't be executed
}


(lib 'matrix)

;; in : initialized dist and next matrices
;; out : dist and next matrices
;; O(n^3)

(define (floyd-with-path n dist next (d 0))
    (for* ((k n) (i n) (j n))
     #:break (< (array-ref dist j j) 0) => 'negative-cycle
    (set! d (+ (array-ref dist i k) (array-ref dist k j)))
     (when (< d (array-ref dist i j))
         (array-set! dist i j d)
         (array-set! next i j (array-ref next i k)))))

;; utilities

;; init random edges costs, matrix 66% filled
(define (init-edges n dist next)
   (for* ((i n) (j n))
    (array-set! dist i i 0)
    (array-set! next i j null)
    #:continue (= j i)
    (array-set! dist i j Infinity)
     #:continue (< (random) 0.3)
     (array-set! dist i j (1+ (random 100)))
    (array-set! next i j j)))

;; show path from u to v
(define (path u v)
    (cond
     ((= u v) (list u))
     ((null? (array-ref next u v)) null)
     (else (cons u (path (array-ref next u v) v)))))

(define( mdist u v) ;; show computed distance
      (array-ref dist u v))

(define (task)
     (init-edges n dist next)
     (array-print dist) ;; show init distances
     (floyd-with-path n dist next))


i = 0
while true do
    i = i + 1
    if i > 10 then break end
end


try
   % do some stuff
catch
   % in case of error, continue here
end


/* goto */
block(..., label, ..., go(label), ...);

/* throw, which is like trapping errors, and can do non-local jumps to return a value */
catch(..., throw(value), ...);

/* error trapping */
errcatch(..., error("Bad luck!"), ...);


defmodule Floyd_Warshall do
  def main(n, edge) do
    {dist, next} = setup(n, edge)
    {dist, next} = shortest_path(n, dist, next)
    print(n, dist, next)
  end

  defp setup(n, edge) do
    big = 1.0e300
    dist = for i <- 1..n, j <- 1..n, into: %{}, do: {{i,j},(if i==j, do: 0, else: big)}
    next = for i <- 1..n, j <- 1..n, into: %{}, do: {{i,j}, nil}
    Enum.reduce(edge, {dist,next}, fn {u,v,w},{dst,nxt} ->
      { Map.put(dst, {u,v}, w), Map.put(nxt, {u,v}, v) }
    end)
  end

  defp shortest_path(n, dist, next) do
    (for k <- 1..n, i <- 1..n, j <- 1..n, do: {k,i,j})
    |> Enum.reduce({dist,next}, fn {k,i,j},{dst,nxt} ->
         if dst[{i,j}] > dst[{i,k}] + dst[{k,j}] do
           {Map.put(dst, {i,j}, dst[{i,k}] + dst[{k,j}]), Map.put(nxt, {i,j}, nxt[{i,k}])}
         else
           {dst, nxt}
         end
       end)
  end

  defp print(n, dist, next) do
    IO.puts "pair     dist    path"
    for i <- 1..n, j <- 1..n, i != j,
        do: :io.format "~w -> ~w  ~4w     ~s~n", [i, j, dist[{i,j}], path(next, i, j)]
  end

  defp path(next, i, j), do: path(next, i, j, [i]) |> Enum.join(" -> ")

  defp path(_next, i, i, list), do: Enum.reverse(list)
  defp path(next, i, j, list) do
    u = next[{i,j}]
    path(next, u, j, [u | list])
  end
end

edge = [{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}]
Floyd_Warshall.main(4, edge)


//Floyd's algorithm: Nigel Galloway August 5th 2018
let Floyd (n:'a[]) (g:Map<('a*'a),int>)= //nodes graph(Map of adjacency list)
  let ix n g=Seq.init (pown g n) (fun x->List.unfold(fun (a,b)->if a=0 then None else Some(b%g,(a-1,b/g)))(n,x))
  let fN w (i,j,k)=match Map.tryFind(i,j) w,Map.tryFind(i,k) w,Map.tryFind(k,j) w with
                        |(None  ,Some j,Some k)->Some(j+k)
                        |(Some i,Some j,Some k)->if (j+k) < i then Some(j+k) else None
                        |_                     ->None
  let n,z=ix 3 (Array.length n)|>Seq.choose(fun (i::j::k::_)->if i<>j&&i<>k&&j<>k then Some(n.[i],n.[j],n.[k]) else None)
       |>Seq.fold(fun (n,n') ((i,j,k) as g)->match fN n g with |Some g->(Map.add (i,j) g n,Map.add (i,j) k n')|_->(n,n')) (g,Map.empty)
  (n,(fun x y->seq{
               let rec fN n g=seq{
                 match Map.tryFind (n,g) z with
                 |Some r->yield! fN n r; yield Some r;yield! fN r g
                 |_->yield None}
               yield! fN x y |> Seq.choose id; yield y}))


loop xx = 1 to 10
  if xx = 1 then leave -- loop terminated by leave
  say 'unreachable'
  end


block outer:
  for i in 0..1000:
    for j in 0..1000:
      if i + j == 3:
        break outer


exception Found of int

let () =
  (* search the first number in a list greater than 50 *)
  try
    let nums = [36; 23; 44; 51; 28; 63; 17] in
    List.iter (fun v -> if v > 50 then raise(Found v)) nums;
    print_endline "nothing found"
  with Found res ->
    Printf.printf "found %d\n" res


module floyd_warshall_algorithm

  use, intrinsic :: ieee_arithmetic

  implicit none

  integer, parameter :: floating_point_kind = &
       & ieee_selected_real_kind (6, 37)
  integer, parameter :: fpk = floating_point_kind

  integer, parameter :: nil_vertex = 0

  type :: edge
     integer :: u
     real(kind = fpk) :: weight
     integer :: v
  end type edge

  type :: edge_list
     type(edge), allocatable :: element(:)
  end type edge_list

contains

  subroutine make_example_graph (edges)
    type(edge_list), intent(out) :: edges

    allocate (edges%element(1:5))
    edges%element(1) = edge (1, -2.0, 3)
    edges%element(2) = edge (3, +2.0, 4)
    edges%element(3) = edge (4, -1.0, 2)
    edges%element(4) = edge (2, +4.0, 1)
    edges%element(5) = edge (2, +3.0, 3)
  end subroutine make_example_graph

  function find_max_vertex (edges) result (n)
    type(edge_list), intent(in) :: edges
    integer n

    integer i

    n = 1
    do i = lbound (edges%element, 1), ubound (edges%element, 1)
       n = max (n, edges%element(i)%u)
       n = max (n, edges%element(i)%v)
    end do
  end function find_max_vertex

  subroutine floyd_warshall (edges, max_vertex, distance, next_vertex)

    type(edge_list), intent(in) :: edges
    integer, intent(out) :: max_vertex
    real(kind = fpk), allocatable, intent(out) :: distance(:,:)
    integer, allocatable, intent(out) :: next_vertex(:,:)

    integer :: n
    integer :: i, j, k
    integer :: u, v
    real(kind = fpk) :: dist_ikj
    real(kind = fpk) :: infinity

    n = find_max_vertex (edges)
    max_vertex = n

    allocate (distance(1:n, 1:n))
    allocate (next_vertex(1:n, 1:n))

    infinity = ieee_value (1.0_fpk,  ieee_positive_inf)

    ! Initialize.

    do i = 1, n
       do j = 1, n
          distance(i, j) = infinity
          next_vertex (i, j) = nil_vertex
       end do
    end do
    do i = lbound (edges%element, 1), ubound (edges%element, 1)
       u = edges%element(i)%u
       v = edges%element(i)%v
       distance(u, v) = edges%element(i)%weight
       next_vertex(u, v) = v
    end do
    do i = 1, n
       distance(i, i) = 0.0_fpk ! Distance from a vertex to itself.
       next_vertex(i, i) = i
    end do

    ! Perform the algorithm.

    do k = 1, n
       do i = 1, n
          do j = 1, n
             dist_ikj = distance(i, k) + distance(k, j)
             if (dist_ikj < distance(i, j)) then
                distance(i, j) = dist_ikj
                next_vertex(i, j) = next_vertex(i, k)
             end if
          end do
       end do
    end do

  end subroutine floyd_warshall

  subroutine print_path (next_vertex, u, v)
    integer, intent(in) :: next_vertex(:,:)
    integer, intent(in) :: u, v

    integer i

    if (next_vertex(u, v) /= nil_vertex) then
       i = u
       write (*, '(I0)', advance = 'no') i
       do while (i /= v)
          i = next_vertex(i, v)
          write (*, '('' -> '', I0)', advance = 'no') i
       end do
    end if
  end subroutine print_path

end module floyd_warshall_algorithm

program floyd_warshall_task

  use, non_intrinsic :: floyd_warshall_algorithm

  implicit none

  type(edge_list) :: example_graph
  integer :: max_vertex
  real(kind = fpk), allocatable :: distance(:,:)
  integer, allocatable :: next_vertex(:,:)
  integer :: u, v

  call make_example_graph (example_graph)
  call floyd_warshall (example_graph, max_vertex, distance, &
       &               next_vertex)

1000 format (1X, I0, ' -> ', I0, 5X, F4.1, 6X)

  write (*, '(''  pair     distance    path'')')
  write (*, '(''---------------------------------------'')')
  do u = 1, max_vertex
     do v = 1, max_vertex
        if (u /= v) then
           write (*, 1000, advance = 'no') u, v, distance(u, v)
           call print_path (next_vertex, u, v)
           write (*, '()', advance = 'yes')
        end if
     end do
  end do

end program floyd_warshall_task


case {OS.rand} mod 3
of 0 then {Foo}
[] 1 then {Bar}
[] 2 then {Buzz}
end


label
  jumpto;
begin
  ...
jumpto:
  some statement;
  ...
  goto jumpto;
  ...
end;


' FB 1.05.0 Win64

Const POSITIVE_INFINITY As Double = 1.0/0.0

Sub printResult(dist(any, any) As Double, nxt(any, any) As Integer)
  Dim As Integer u, v
  Print("pair     dist    path")
  For i As Integer = 0 To UBound(nxt, 1)
    For j As Integer = 0 To UBound(nxt, 1)
      If i <> j Then
        u = i + 1
        v = j + 1
        Print Str(u); " -> "; Str(v); "    "; dist(i, j); "     "; Str(u);
        Do
          u = nxt(u - 1, v - 1)
          Print " -> "; Str(u);
        Loop While u <> v
        Print
      End If
    Next j
  Next i
End Sub

Sub floydWarshall(weights(Any, Any) As Integer, numVertices As Integer)
  Dim dist(0 To numVertices - 1, 0 To numVertices - 1) As Double
  For i As Integer = 0 To numVertices - 1
    For j As Integer = 0 To numVertices - 1
      dist(i, j) = POSITIVE_INFINITY
    Next j
  Next i

  For x As Integer = 0 To UBound(weights, 1)
    dist(weights(x, 0) - 1, weights(x, 1) - 1) = weights(x, 2)
  Next x

  Dim nxt(0 To numVertices - 1, 0 To numVertices - 1) As Integer
  For i As Integer = 0 To numVertices - 1
    For j As Integer = 0 To numVertices - 1
      If i <> j Then nxt(i, j) = j + 1
    Next j
  Next i

  For k As Integer = 0 To numVertices - 1
    For i As Integer = 0 To numVertices - 1
      For j As Integer = 0 To numVertices - 1
        If (dist(i, k) + dist(k, j)) < dist(i, j) Then
          dist(i, j) = dist(i, k) + dist(k, j)
          nxt(i, j) = nxt(i, k)
        End If
      Next j
    Next i
  Next k

  printResult(dist(), nxt())
End Sub

Dim weights(4, 2) As Integer = {{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}}
Dim numVertices As Integer = 4
floydWarshall(weights(), numVertices)
Print
Print "Press any key to quit"
Sleep


without js -- (no goto in JavaScript)
procedure p()
    goto :but_print
    puts(1,"This will not be printed...\n")
::but_print
    puts(1,"...but this will\n")
end procedure
p()


<?php
goto a;
echo 'Foo';

a:
echo 'Bar';
?>


LEAVE
   The LEAVE statement terminates execution of a loop.
   Execution resumes at the next statement after the loop.
ITERATE
   The ITERATE statement causes the next iteration of the loop to
   commence.  Any statements between ITERATE and the end of the loop
   are not executed.
STOP
   Terminates execution of either a task or the entire program.
SIGNAL FINISH
   Terminates execution of a program in a nice way.
SIGNAL statement
   SIGNAL <condition> raises the named condition.  The condition may
   be one of the hardware or software conditions such as OVERFLOW,
   UNDERFLOW, ZERODIVIDE, SUBSCRIPTRANGE, STRINGRANGE, etc, or a
   user-defined condition.
CALL
   The CALL statement causes control to transfer to the named
   subroutine.
SELECT
   The SELECT statement permits the execution of just one of a
   list of statements (or groups of statements).
   It is sort of like a computed GOTO.
GO TO
   The GO TO statement causes control to be transferred to the named
   statement.
   It can also be used to transfer control to any one of an array of
   labelled statements. (This form is superseded by SELECT, above.)
   [GO TO  can also be spelled as  GOTO].


package main

import (
  "fmt"
  "strconv"
)

// A Graph is the interface implemented by graphs that
// this algorithm can run on.
type Graph interface {
  Vertices() []Vertex
  Neighbors(v Vertex) []Vertex
  Weight(u, v Vertex) int
}

// Nonnegative integer ID of vertex
type Vertex int

// ig is a graph of integers that satisfies the Graph interface.
type ig struct {
  vert  []Vertex
  edges map[Vertex]map[Vertex]int
}

func (g ig) edge(u, v Vertex, w int) {
  if _, ok := g.edges[u]; !ok {
    g.edges[u] = make(map[Vertex]int)
  }
  g.edges[u][v] = w
}
func (g ig) Vertices() []Vertex { return g.vert }
func (g ig) Neighbors(v Vertex) (vs []Vertex) {
  for k := range g.edges[v] {
    vs = append(vs, k)
  }
  return vs
}
func (g ig) Weight(u, v Vertex) int { return g.edges[u][v] }
func (g ig) path(vv []Vertex) (s string) {
  if len(vv) == 0 {
    return ""
  }
  s = strconv.Itoa(int(vv[0]))
  for _, v := range vv[1:] {
    s += " -> " + strconv.Itoa(int(v))
  }
  return s
}

const Infinity = int(^uint(0) >> 1)

func FloydWarshall(g Graph) (dist map[Vertex]map[Vertex]int, next map[Vertex]map[Vertex]*Vertex) {
  vert := g.Vertices()
  dist = make(map[Vertex]map[Vertex]int)
  next = make(map[Vertex]map[Vertex]*Vertex)
  for _, u := range vert {
    dist[u] = make(map[Vertex]int)
    next[u] = make(map[Vertex]*Vertex)
    for _, v := range vert {
      dist[u][v] = Infinity
    }
    dist[u][u] = 0
    for _, v := range g.Neighbors(u) {
      v := v
      dist[u][v] = g.Weight(u, v)
      next[u][v] = &v
    }
  }
  for _, k := range vert {
    for _, i := range vert {
      for _, j := range vert {
        if dist[i][k] < Infinity && dist[k][j] < Infinity {
          if dist[i][j] > dist[i][k]+dist[k][j] {
            dist[i][j] = dist[i][k] + dist[k][j]
            next[i][j] = next[i][k]
          }
        }
      }
    }
  }
  return dist, next
}

func Path(u, v Vertex, next map[Vertex]map[Vertex]*Vertex) (path []Vertex) {
  if next[u][v] == nil {
    return
  }
  path = []Vertex{u}
  for u != v {
    u = *next[u][v]
    path = append(path, u)
  }
  return path
}

func main() {
  g := ig{[]Vertex{1, 2, 3, 4}, make(map[Vertex]map[Vertex]int)}
  g.edge(1, 3, -2)
  g.edge(3, 4, 2)
  g.edge(4, 2, -1)
  g.edge(2, 1, 4)
  g.edge(2, 3, 3)

  dist, next := FloydWarshall(g)
  fmt.Println("pair\tdist\tpath")
  for u, m := range dist {
    for v, d := range m {
      if u != v {
        fmt.Printf("%d -> %d\t%3d\t%s\n", u, v, d, g.path(Path(u, v, next)))
      }
    }
  }
}


while condition1 do
   while condition2 do
      if condition3 then
         quitloop(2);
      endif;
   endwhile;
endwhile;


If OpenConsole()
  top:
  i = i + 1
  PrintN("Hello world.")
  If i < 10
    Goto top
  EndIf

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


# Search for an odd factor of a using brute force:
for i in range(n):
    if (n%2) == 0:
        continue
    if (n%i) == 0:
        result = i
        break
else:
    result = None
    print "No odd factors found"


#lang racket

;; some silly boilerplate to mimic the assembly code better
(define r0 0)
(define (cmp r1 r2) (set! r0 (sgn (- r1 r2))))
(define (je true-label false-label) (if (zero? r0) (true-label) (false-label)))
(define (goto label) (label))

(define (gcd %eax %ecx)
  (define %edx 0)
  (define (main) (goto loop))
  (define (loop) (cmp 0 %ecx)
                 (je end cont))
  (define (cont) (set!-values [%eax %edx] (quotient/remainder %eax %ecx))
                 (set! %eax %ecx)
                 (set! %ecx %edx)
                 (goto loop))
  (define (end)  (printf "result: ~s\n" %eax)
                 (return %eax))
  (main))


class FloydWarshall {
    static void main(String[] args) {
        int[][] weights = [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]]
        int numVertices = 4

        floydWarshall(weights, numVertices)
    }

    static void floydWarshall(int[][] weights, int numVertices) {
        double[][] dist = new double[numVertices][numVertices]
        for (double[] row : dist) {
            Arrays.fill(row, Double.POSITIVE_INFINITY)
        }

        for (int[] w : weights) {
            dist[w[0] - 1][w[1] - 1] = w[2]
        }

        int[][] next = new int[numVertices][numVertices]
        for (int i = 0; i < next.length; i++) {
            for (int j = 0; j < next.length; j++) {
                if (i != j) {
                    next[i][j] = j + 1
                }
            }
        }

        for (int k = 0; k < numVertices; k++) {
            for (int i = 0; i < numVertices; i++) {
                for (int j = 0; j < numVertices; j++) {
                    if (dist[i][k] + dist[k][j] < dist[i][j]) {
                        dist[i][j] = dist[i][k] + dist[k][j]
                        next[i][j] = next[i][k]
                    }
                }
            }
        }

        printResult(dist, next)
    }

    static void printResult(double[][] dist, int[][] next) {
        println("pair     dist    path")
        for (int i = 0; i < next.length; i++) {
            for (int j = 0; j < next.length; j++) {
                if (i != j) {
                    int u = i + 1
                    int v = j + 1
                    String path = String.format("%d -> %d    %2d     %s", u, v, (int) dist[i][j], u)
                    boolean loop = true
                    while (loop) {
                        u = next[u - 1][v - 1]
                        path += " -> " + u
                        loop = u != v
                    }
                    println(path)
                }
            }
        }
    }
}


rebol [
	Title: "Flow Control"
	URL: http://rosettacode.org/wiki/Flow_Control_Structures
]

; return -- Return early from function (normally, functions return
; result of last evaluation).

hatefive: func [
	"Prints value unless it's the number 5."
	value "Value to print."
][
	if value = 5 [return "I hate five!"]
	print value
]

print "Function hatefive, with various values:"
hatefive 99
hatefive 13
hatefive 5
hatefive 3

; break -- Break out of current loop.

print [crlf "Loop to 10, but break out at five:"]
repeat i 10 [
	if i = 5 [break]
	print i
]

; catch/throw -- throw breaks out of a code block to enclosing catch.

print [crlf "Start to print two lines, but throw out after the first:"]
catch [
	print "First"
	throw "I'm done!"
	print "Second"
]

; Using named catch blocks, you can select which catcher you want when throwing.

print [crlf "Throw from inner code block, caught by outer:"]
catch/name [
	print "Outer catch block."
	catch/name [
		print "Inner catch block."
		throw/name "I'm done!" 'Johnson
		print "We never get here."
	] 'Clemens
	print "We never get here, either."
] 'Johnson

; try

div: func [
	"Divide first number by second."
	a b
	/local r "Result"
][
	if error? try [r: a / b] [r: "Error!"]
	r ; Functions return last value evaluated.
]

print [crlf "Report error on bad division:"]
print div 10 4
print div 10 2
print div 10 1
print div 10 0


call  routineName                      /*no arguments passed to routine.*/
call  routineName  50                  /*one argument (fifty) passed.   */
call  routineName  50,60               /*two arguments        passed.   */
call  routineName  50, 60              /*(same as above)                */
call  routineName  50 ,60              /*(same as above)                */
call  routineName  10*5 , 8**4 - 4     /*(same as above)                */
call  routineName  50 , , , 70         /*4 args passed, 2nd&3rd omitted.*/
                                       /*omitted args are   NOT  null.  */
call  routineName  ,,,,,,,,,,,,,,,,800 /*17 args passed, 16 omitted.    */
call   date                            /*looks for DATE internally first*/
call  'DATE'                           /*  "    "    "  BIF | externally*/


import Control.Monad (join)
import Data.List (union)
import Data.Map hiding (foldr, union)
import Data.Maybe (fromJust, isJust)
import Data.Semigroup
import Prelude hiding (lookup, filter)


#
# Floyd-Warshall algorithm.
#
# See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
#

record fw_results (n, distance, next_vertex)

link array
link numbers
link printf

procedure main ()
  local example_graph
  local fw
  local u, v

  example_graph := [[1, -2.0, 3],
                    [3, +2.0, 4],
                    [4, -1.0, 2],
                    [2, +4.0, 1],
                    [2, +3.0, 3]]

  fw := floyd_warshall (example_graph)

  printf ("  pair    distance   path\n")
  printf ("-------------------------------------\n")
  every u := 1 to fw.n do {
    every v := 1 to fw.n do {
      if u ~= v then {
        printf (" %d -> %d    %4s     %s\n", u, v,
                string (ref_array (fw.distance, u, v)),
                path_to_string (find_path (fw.next_vertex, u, v)))
      }
    }
  }
end

procedure floyd_warshall (edges)
  local n, distance, next_vertex
  local e
  local i, j, k
  local dist_ij, dist_ik, dist_kj, dist_ikj

  n := max_vertex (edges)
  distance := create_array ([1, 1], [n, n], &null)
  next_vertex := create_array ([1, 1], [n, n], &null)

  # Initialization.
  every e := !edges do {
    ref_array (distance, e[1], e[3]) := e[2]
    ref_array (next_vertex, e[1], e[3]) := e[3]
  }
  every i := 1 to n do {
    ref_array (distance, i, i) := 0.0 # Distance to self = 0.
    ref_array (next_vertex, i, i) := i
  }

  # Perform the algorithm. Here &null will play the role of
  # "infinity": "\" means a value is finite, "/" that it is infinite.
  every k := 1 to n do {
    every i := 1 to n do {
      every j := 1 to n do {
        dist_ij := ref_array (distance, i, j)
        dist_ik := ref_array (distance, i, k)
        dist_kj := ref_array (distance, k, j)
        if \dist_ik & \dist_kj then {
          dist_ikj := dist_ik + dist_kj
          if /dist_ij | dist_ikj < dist_ij then {
            ref_array (distance, i, j) := dist_ikj
            ref_array (next_vertex, i, j) :=
                ref_array (next_vertex, i, k)
          }
        }
      }
    }
  }

  return fw_results (n, distance, next_vertex)
end

procedure find_path (next_vertex, u, v)
  local path

  if / (ref_array (next_vertex, u, v)) then {
    path := []
  } else {
    path := [u]
    while u ~= v do {
      u := ref_array (next_vertex, u, v)
      put (path, u)
    }
  }
  return path
end

procedure path_to_string (path)
  local s

  if *path = 0 then {
    s := ""
  } else {
    s := string (path[1])
    every s ||:= (" -> " || !path[2 : 0])
  }
  return s
end

procedure max_vertex (edges)
  local e
  local m

  *edges = 0 & stop ("no edges")
  m := 1
  every e := !edges do m := max (m, e[1], e[3])
  return m
end


i = 1
while true
      see i + nl
      if i = 10 see "Break!" exit ok
      i = i + 1
end


begin
  # some code that may raise an exception
rescue ExceptionClassA => a
  # handle code
rescue ExceptionClassB, ExceptionClassC => b_or_c
  # handle ...
rescue
  # handle all other exceptions
else
  # when no exception occurred, execute this code
ensure
  # execute this code always
end


/* GOTO: as in other languages
   STOP: to stop current data step */
data _null_;
	n=1;
	p=1;
L1:
	put n p;
	n=n+1;
	if n<=p then goto L1;
	p=p+1;
	n=1;
	if p>10 then stop;
	goto L1;

run;

/* LINK: equivalent of GOSUB in BASIC
   RETURN: after a LINK, or to return to the beginning of data step */
data _null_;
input a b;
link gcd;
put a b gcd;
return;

gcd:
	_a=a;
	_b=b;
	do while(_b>0);
	_r=mod(_a,_b);
	_a=_b;
	_b=_r;
	end;
	gcd=_a;
	return;

cards;
2 15
533 221
8 44
;
run;


import Goto._
import scala.util.continuations._

object Goto {

  case class Label(k: Label => Unit)

  private case class GotoThunk(label: Label) extends Throwable

  def label: Label @suspendable =
    shift((k: Label => Unit) => executeFrom(Label(k)))

  def goto(l: Label): Nothing =
    throw new GotoThunk(l)

  private def executeFrom(label: Label): Unit = {
    val nextLabel = try {
      label.k(label)
      None
    } catch {
      case g: GotoThunk => Some(g.label)
    }
    if (nextLabel.isDefined) executeFrom(nextLabel.get)
  }

}


floyd=: verb define
  for_j. i.#y do.
    y=. y <. j ({"1 +/ {) y
  end.
)


import static java.lang.String.format;
import java.util.Arrays;

public class FloydWarshall {

    public static void main(String[] args) {
        int[][] weights = {{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}};
        int numVertices = 4;

        floydWarshall(weights, numVertices);
    }

    static void floydWarshall(int[][] weights, int numVertices) {

        double[][] dist = new double[numVertices][numVertices];
        for (double[] row : dist)
            Arrays.fill(row, Double.POSITIVE_INFINITY);

        for (int[] w : weights)
            dist[w[0] - 1][w[1] - 1] = w[2];

        int[][] next = new int[numVertices][numVertices];
        for (int i = 0; i < next.length; i++) {
            for (int j = 0; j < next.length; j++)
                if (i != j)
                    next[i][j] = j + 1;
        }

        for (int k = 0; k < numVertices; k++)
            for (int i = 0; i < numVertices; i++)
                for (int j = 0; j < numVertices; j++)
                    if (dist[i][k] + dist[k][j] < dist[i][j]) {
                        dist[i][j] = dist[i][k] + dist[k][j];
                        next[i][j] = next[i][k];
                    }

        printResult(dist, next);
    }

    static void printResult(double[][] dist, int[][] next) {
        System.out.println("pair     dist    path");
        for (int i = 0; i < next.length; i++) {
            for (int j = 0; j < next.length; j++) {
                if (i != j) {
                    int u = i + 1;
                    int v = j + 1;
                    String path = format("%d -> %d    %2d     %s", u, v,
                            (int) dist[i][j], u);
                    do {
                        u = next[u - 1][v - 1];
                        path += " -> " + u;
                    } while (u != v);
                    System.out.println(path);
                }
            }
        }
    }
}


say "Hello"
goto :world
say "Never printed"
@:world
say "World"


mata
function pythagorean_triple(n) {
	for (a=1; a<=n; a++) {
		for (b=a; b<=n-a; b++) {
			c=n-a-b
			if (c>b & c*c==a*a+b*b) {
				printf("%f %f %f\n",a,b,c)
				goto END
			}
		}
	}
	END:
}

pythagorean_triple(1980)
165 900 915


    REM TinyBASIC has only two control flow structures: goto and gosub
    LET N = 0
 10 LET N = N + 1
    PRINT N
    IF N < 10 THEN GOTO 10

    LET R = 10

 15 IF N < 10000 THEN GOSUB 20
    IF N > 10000 THEN GOTO 30
    GOTO R + 5    REM goto can be computed

 20 LET N = N * 2
    PRINT N
    RETURN    REM gosub returns to where it was called from
              REM meaning it can be called from multiple
              REM places in the program

 30 LET N = 0
 40 GOSUB 105-N    REM gosub can be computed as well
    IF N <= 5 THEN GOTO 40
    END

100 PRINT "ZERO"
101 PRINT "1"
102 PRINT "22"
103 PRINT "333"
104 PRINT "4444"
105 PRINT "55555"
    LET N = N + 1
    RETURN    REM one return can serve several gosubs


  Sub bar2()
      Dim x = 0
      GoTo label
      x = 5
label:
      Console.WriteLine(x)
  End Sub


var func = Fn.new { |n|
    var i = 1
    while (true) {
        if (i == 1) {
            i = i + 1
            continue // jumps to next iteration
        }
        System.print(i)
        if (i == n) break // exits while loop
        i = i + 1
    }
    if (n < 3) return // exits function
    System.print(n + 1)
}

var fiber = Fiber.new {
    Fiber.abort("Demo error") // error occcurred, abort script
}

var a = [2, 3]
for (n in a) {
    func.call(n)
    if (n > 2) return // end module and hence the script as its a single module script
    var error = fiber.try() // catch any error
    System.print("Caught error: " + error)
}


gosub subrutina

label bucle
print "Bucle infinito"
goto bucle
end

label subrutina
print "En subrutina"
wait 10
return
end


PrintString:
ld a,(hl)       ;HL is our pointer to the string we want to print
cp 0            ;it's better to use OR A to compare A to zero, but for demonstration purposes this is easier to read.
ret z           ;return if accumulator = zero
call PrintChar  ;prints accumulator's ascii code to screen - on Amstrad CPC for example this label points to memory address &BB5A
inc hl          ;next char
jr PrintString  ;jump back to the start of the loop. RET Z is our only exit.


continue; continue(n);  // continue nth nested loop
break; break(n);  // break out of nth nested loop
try{ ... }catch(exception){ ... } [else{ ... }]
onExit(fcn);  // run fcn when enclosing function exits


# Floyd-Warshall algorithm: https://rosettacode.org/wiki/Floyd-Warshall_algorithm
# v0.6

function floydwarshall(weights::Matrix, nvert::Int)
    dist = fill(Inf, nvert, nvert)
    for i in 1:size(weights, 1)
        dist[weights[i, 1], weights[i, 2]] = weights[i, 3]
    end
    # return dist
    next = collect(j != i ? j : 0 for i in 1:nvert, j in 1:nvert)

    for k in 1:nvert, i in 1:nvert, j in 1:nvert
        if dist[i, k] + dist[k, j] < dist[i, j]
            dist[i, j] = dist[i, k] + dist[k, j]
            next[i, j] = next[i, k]
        end
    end

    # return next
    function printresult(dist, next)
        println("pair     dist    path")
        for i in 1:size(next, 1), j in 1:size(next, 2)
            if i != j
                u = i
                path = @sprintf "%d -> %d    %2d     %s" i j dist[i, j] i
                while true
                    u = next[u, j]
                    path *= " -> $u"
                    if u == j break end
                end
                println(path)
            end
        end
    end
    printresult(dist, next)
end

floydwarshall([1 3 -2; 2 1 4; 2 3 3; 3 4 2; 4 2 -1], 4)


// version 1.1

object FloydWarshall {
    fun doCalcs(weights: Array<IntArray>, nVertices: Int) {
        val dist = Array(nVertices) { DoubleArray(nVertices) { Double.POSITIVE_INFINITY } }
        for (w in weights) dist[w[0] - 1][w[1] - 1] = w[2].toDouble()
        val next = Array(nVertices) { IntArray(nVertices) }
        for (i in 0 until next.size) {
            for (j in 0 until next.size) {
                if (i != j) next[i][j] = j + 1
            }
        }
        for (k in 0 until nVertices) {
            for (i in 0 until nVertices) {
                for (j in 0 until nVertices) {
                    if (dist[i][k] + dist[k][j] < dist[i][j]) {
                        dist[i][j] = dist[i][k] + dist[k][j]
                        next[i][j] = next[i][k]
                    }
                }
            }
        }
        printResult(dist, next)
    }

    private fun printResult(dist: Array<DoubleArray>, next: Array<IntArray>) {
        var u: Int
        var v: Int
        var path: String
        println("pair     dist    path")
        for (i in 0 until next.size) {
            for (j in 0 until next.size) {
                if (i != j) {
                    u = i + 1
                    v = j + 1
                    path = ("%d -> %d    %2d     %s").format(u, v, dist[i][j].toInt(), u)
                    do {
                        u = next[u - 1][v - 1]
                        path += " -> " + u
                    } while (u != v)
                    println(path)
                }
            }
        }
    }
}

fun main(args: Array<String>) {
    val weights = arrayOf(
            intArrayOf(1, 3, -2),
            intArrayOf(2, 1, 4),
            intArrayOf(2, 3, 3),
            intArrayOf(3, 4, 2),
            intArrayOf(4, 2, -1)
    )
    val nVertices = 4
    FloydWarshall.doCalcs(weights, nVertices)
}


function printResult(dist, nxt)
    print("pair     dist    path")
    for i=0, #nxt do
        for j=0, #nxt do
            if i ~= j then
                u = i + 1
                v = j + 1
                path = string.format("%d -> %d    %2d     %s", u, v, dist[i][j], u)
                repeat
                    u = nxt[u-1][v-1]
                    path = path .. " -> " .. u
                until (u == v)
                print(path)
            end
        end
    end
end

function floydWarshall(weights, numVertices)
    dist = {}
    for i=0, numVertices-1 do
        dist[i] = {}
        for j=0, numVertices-1 do
            dist[i][j] = math.huge
        end
    end

    for _,w in pairs(weights) do
        -- the weights array is one based
        dist[w[1]-1][w[2]-1] = w[3]
    end

    nxt = {}
    for i=0, numVertices-1 do
        nxt[i] = {}
        for j=0, numVertices-1 do
            if i ~= j then
                nxt[i][j] = j+1
            end
        end
    end

    for k=0, numVertices-1 do
        for i=0, numVertices-1 do
            for j=0, numVertices-1 do
                if dist[i][k] + dist[k][j] < dist[i][j] then
                    dist[i][j] = dist[i][k] + dist[k][j]
                    nxt[i][j] = nxt[i][k]
                end
            end
        end
    end

    printResult(dist, nxt)
end

weights = {
    {1, 3, -2},
    {2, 1, 4},
    {2, 3, 3},
    {3, 4, 2},
    {4, 2, -1}
}
numVertices = 4
floydWarshall(weights, numVertices)


g = Graph[{1 \[DirectedEdge] 3, 3 \[DirectedEdge] 4,
   4 \[DirectedEdge] 2, 2 \[DirectedEdge] 1, 2 \[DirectedEdge] 3},
  EdgeWeight -> {(1 \[DirectedEdge] 3) -> -2, (3 \[DirectedEdge] 4) ->
      2, (4 \[DirectedEdge] 2) -> -1, (2 \[DirectedEdge] 1) ->
     4, (2 \[DirectedEdge] 3) -> 3}]
vl = VertexList[g];
dm = GraphDistanceMatrix[g];
Grid[LexicographicSort[
  DeleteCases[
   Catenate[
    Table[{vl[[i]], vl[[j]], dm[[i, j]]}, {i, Length[vl]}, {j,
      Length[vl]}]], {x_, x_, _}]]]