vplus = function(v1, v2)
    return [v1[0]+v2[0],v1[1]+v2[1]]
end function

vminus = function (v1, v2)
    return [v1[0]-v2[0],v1[1]-v2[1]]
end function

vmult = function(v1, scalar)
    return [v1[0]*scalar, v1[1]*scalar]
end function

vdiv = function(v1, scalar)
    return [v1[0]/scalar, v1[1]/scalar]
end function

vector1 = [2,3]
vector2 = [4,5]

print vplus(vector1,vector2)
print vminus(vector2, vector1)
print vmult(vector1, 3)
print vdiv(vector2, 2)


MODULE Vector;
FROM FormatString IMPORT FormatString;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

TYPE Vector =
    RECORD
        x,y : REAL;
    END;

PROCEDURE Add(a,b : Vector) : Vector;
BEGIN
    RETURN Vector{a.x+b.x, a.y+b.y}
END Add;

PROCEDURE Sub(a,b : Vector) : Vector;
BEGIN
    RETURN Vector{a.x-b.x, a.y-b.y}
END Sub;

PROCEDURE Mul(v : Vector; r : REAL) : Vector;
BEGIN
    RETURN Vector{a.x*r, a.y*r}
END Mul;

PROCEDURE Div(v : Vector; r : REAL) : Vector;
BEGIN
    RETURN Vector{a.x/r, a.y/r}
END Div;

PROCEDURE Print(v : Vector);
VAR buf : ARRAY[0..64] OF CHAR;
BEGIN
    WriteString("<");

    RealToStr(v.x, buf);
    WriteString(buf);
    WriteString(", ");

    RealToStr(v.y, buf);
    WriteString(buf);
    WriteString(">")
END Print;

VAR a,b : Vector;
BEGIN
    a := Vector{5.0, 7.0};
    b := Vector{2.0, 3.0};

    Print(Add(a, b));
    WriteLn;
    Print(Sub(a, b));
    WriteLn;
    Print(Mul(a, 11.0));
    WriteLn;
    Print(Div(a, 2.0));
    WriteLn;

    ReadChar
END Vector.


class Vector
        declare x
        declare y

        def Vector(x, y)
                this.x = float(x)
                this.y = float(y)
        end

        def operator+(other)
                return new(Vector, this.x + other.x, this.y + other.y)
        end

        def operator-(other)
                return new(Vector, this.x - other.x, this.y - other.y)
        end

        def operator/(val)
                return new(Vector, this.x / val, this.y / val)
        end

        def operator*(val)
                return new(Vector, this.x * val, this.y * val)
        end

        def toString()
                return format("[%s, %s]", this.x, this.y)
        end
end

println new(Vector, 5, 7) + new(Vector, 2, 3)
println new(Vector, 5, 7) - new(Vector, 2, 3)
println new(Vector, 5, 7) * 11
println new(Vector, 5, 7) / 2


import strformat

type Vec2[T: SomeNumber] = tuple[x, y: T]

proc initVec2[T](x, y: T): Vec2[T] = (x, y)

func`+`[T](a, b: Vec2[T]): Vec2[T] = (a.x + b.x, a.y + b.y)

func `-`[T](a, b: Vec2[T]): Vec2[T] = (a.x - b.x, a.y - b.y)

func `*`[T](a: Vec2[T]; m: T): Vec2[T] = (a.x * m, a.y * m)

func `/`[T](a: Vec2[T]; d: T): Vec2[T] =
  if d == 0:
    raise newException(DivByZeroDefect, "division of vector by 0")
  when T is SomeInteger:
    (a.x div d, a.y div d)
  else:
    (a.x / d, a.y / d)

func `$`[T](a: Vec2[T]): string =
  &"({a.x}, {a.y})"

# Three ways to initialize a vector.
let v1 = initVec2(2, 3)
let v2: Vec2[int] = (-1, 2)
let v3 = (x: 4, y: -2)

echo &"{v1} + {v2} = {v1 + v2}"
echo &"{v3} - {v2} = {v3 - v2}"

# Float vectors.
let v4 = initVec2(2.0, 3.0)
let v5 = (x: 3.0, y: 2.0)

echo &"{v4} * 2 = {v4 * 2}"
echo &"{v3} / 2 = {v3 / 2}"   # Int division.
echo &"{v5} / 2 = {v5 / 2}"   # Float division.


class Test {
  function : Main(args : String[]) ~ Nil {
    Vec2->New(5, 7)->Add(Vec2->New(2, 3))->ToString()->PrintLine();
    Vec2->New(5, 7)->Sub(Vec2->New(2, 3))->ToString()->PrintLine();
    Vec2->New(5, 7)->Mult(11)->ToString()->PrintLine();
    Vec2->New(5, 7)->Div(2)->ToString()->PrintLine();
  }
}

class Vec2 {
  @x : Float;
  @y : Float;

  New(x : Float, y : Float) {
    @x := x;
    @y := y;
  }

  method : GetX() ~ Float {
    return @x;
  }

  method : GetY() ~ Float {
    return @y;
  }

  method : public : Add(v : Vec2) ~ Vec2 {
    return Vec2->New(@x + v->GetX(), @y + v->GetY());
  }

  method : public : Sub(v : Vec2) ~ Vec2 {
    return Vec2->New(@x - v->GetX(), @y - v->GetY());
  }

  method : public : Div(val : Float) ~ Vec2 {
    return Vec2->New(@x / val, @y / val);
  }

  method : public : Mult(val : Float) ~ Vec2 {
    return Vec2->New(@x * val, @y * val);
  }

  method : public : ToString() ~ String {
    return "[{[email protected]}, {[email protected]}]";
  }
}


module Vector =
  struct
    type t = { x : float; y : float }
    let make x y = { x; y }
    let add a b = { x = a.x +. b.x; y = a.y +. b.y }
    let sub a b = { x = a.x -. b.x; y = a.y -. b.y }
    let mul a n = { x = a.x *. n; y = a.y *. n }
    let div a n = { x = a.x /. n; y = a.y /. n }

    let to_string {x; y} = Printf.sprintf "(%F, %F)" x y

    let ( + ) = add
    let ( - ) = sub
    let ( * ) = mul
    let ( / ) = div
  end

open Printf

let test () =
  let a, b = Vector.make 5. 7., Vector.make 2. 3. in
  printf "a:    %s\n" (Vector.to_string a);
  printf "b:    %s\n" (Vector.to_string b);
  printf "a+b:  %s\n" Vector.(a + b |> to_string);
  printf "a-b:  %s\n" Vector.(a - b |> to_string);
  printf "a*11: %s\n" Vector.(a * 11. |> to_string);
  printf "a/2:  %s\n" Vector.(a / 2. |> to_string)


(define :+ +)
(define (+ a b)
   (if (vector? a)
      (if (vector? b)
         (vector-map :+ a b)
         (error "error:" "not applicable (+ vector non-vector)"))
      (if (vector? b)
         (error "error:" "not applicable (+ non-vector vector)")
         (:+ a b))))

(define :- -)
(define (- a b)
   (if (vector? a)
      (if (vector? b)
         (vector-map :- a b)
         (error "error:" "not applicable (+ vector non-vector)"))
      (if (vector? b)
         (error "error:" "not applicable (+ non-vector vector)")
         (:- a b))))

(define :* *)
(define (* a b)
   (if (vector? a)
      (if (not (vector? b))
         (vector-map (lambda (x) (:* x b)) a)
         (error "error:" "not applicable (* vector vector)"))
      (if (vector? b)
         (error "error:" "not applicable (* scalar vector)")
         (:* a b))))

(define :/ /)
(define (/ a b)
   (if (vector? a)
      (if (not (vector? b))
         (vector-map (lambda (x) (:/ x b)) a)
         (error "error:" "not applicable (/ vector vector)"))
      (if (vector? b)
         (error "error:" "not applicable (/ scalar vector)")
         (:/ a b))))

(define x [1 2 3 4 5])
(define y [7 8 5 4 2])
(print x " + " y " = " (+ x y))
(print x " - " y " = " (- x y))
(print x " * " 7 " = " (* x 7))
(print x " / " 7 " = " (/ x 7))


v=.vector~new(12,-3);  Say "v=.vector~new(12,-3) =>" v~print
v~ab(1,1,6,4);         Say "v~ab(1,1,6,4)        =>" v~print
v~al(45,2);            Say "v~al(45,2)           =>" v~print
w=v~'+'(v);            Say "w=v~'+'(v)           =>" w~print
x=v~'-'(w);            Say "x=v~'-'(w)           =>" x~print
y=x~'*'(3);            Say "y=x~'*'(3)           =>" y~print
z=x~'/'(0.1);          Say "z=x~'/'(0.1)         =>" z~print

::class vector
::attribute x
::attribute y
::method init
Use Arg a,b
self~x=a
self~y=b

::method ab      /* set vector from point (a,b) to point (c,d)       */
Use Arg a,b,c,d
self~x=c-a
self~y=d-b

::method al      /* set vector given angle a and length l            */
Use Arg a,l
self~x=l*rxCalccos(a)
self~y=l*rxCalcsin(a)

::method '+'     /* add: Return sum of self and argument             */
Use Arg v
x=self~x+v~x
y=self~y+v~y
res=.vector~new(x,y)
Return res

::method '-'     /* subtract: Return difference of self and argument */
Use Arg v
x=self~x-v~x
y=self~y-v~y
res=.vector~new(x,y)
Return res

::method '*'     /* multiply: Return self multiplied by t            */
Use Arg t
x=self~x*t
y=self~y*t
res=.vector~new(x,y)
Return res

::method '/'     /* divide: Return self divided by t                 */
Use Arg t
x=self~x/t
y=self~y/t
res=.vector~new(x,y)
Return res

::method print   /* prettyprint a vector                             */
return '['self~x','self~y']'

::requires rxMath Library


package Vector;
use Moose;
use feature 'say';

use overload '+' => \&add,
             '-' => \&sub,
             '*' => \&mul,
             '/' => \&div,
             '""' => \&stringify;

has 'x' => (is =>'rw', isa => 'Num', required => 1);
has 'y' => (is =>'rw', isa => 'Num', required => 1);

sub add {
  my($a, $b) = @_;
  Vector->new( x => $a->x + $b->x, y => $a->y + $b->y);
}
sub sub {
  my($a, $b) = @_;
  Vector->new( x => $a->x - $b->x, y => $a->y - $b->y);
}
sub mul {
  my($a, $b) = @_;
  Vector->new( x => $a->x * $b, y => $a->y * $b);
}
sub div {
  my($a, $b) = @_;
  Vector->new( x => $a->x / $b, y => $a->y / $b);
}
sub stringify {
  my $self = shift;
  "(" . $self->x . "," . $self->y . ')';
}

package main;

my $a = Vector->new(x => 5, y => 7);
my $b = Vector->new(x => 2, y => 3);
say "a:    $a";
say "b:    $b";
say "a+b:  ",$a+$b;
say "a-b:  ",$a-$b;
say "a*11: ",$a*11;
say "a/2:  ",$a/2;


constant a = {5,7}, b = {2, 3}
?sq_add(a,b)
?sq_sub(a,b)
?sq_mul(a,11)
?sq_div(a,2)


include ..\Utilitys.pmt

def add + enddef
def sub - enddef
def mul * enddef
def div / enddef

def opVect  /# a b op -- a b c #/
    var op
    list? not if swap len rot swap repeat endif
    len var lon

    ( lon 1 -1 ) for var i
        i get rot i get rot op exec >ps swap
    endfor

    lon for drop
        ps>
    endfor

    lon tolist
enddef

( 5 7 ) ( 2 3 )

getid add opVect ?
getid sub opVect ?
drop 2
getid mul opVect ?
getid div opVect ?


(de add (A B)
   (mapcar + A B) )
(de sub (A B)
   (mapcar - A B) )
(de mul (A B)
   (mapcar '((X) (* X B)) A) )
(de div (A B)
   (mapcar '((X) (*/ X B)) A) )
(let (X (5 7)  Y (2 3))
   (println (add X Y))
   (println (sub X Y))
   (println (mul X 11))
   (println (div X 2))  )


*process source attributes xref or(!);
 vectors: Proc Options(main);
 Dcl (v,w,x,y,z) Dec Float(9) Complex;
 real(v)=12; imag(v)=-3;   Put Edit(pp(v))(Skip,a);
 real(v)=6-1; imag(v)=4-1; Put Edit(pp(v))(Skip,a);
 real(v)=2*cosd(45);
 imag(v)=2*sind(45);       Put Edit(pp(v))(Skip,a);

 w=v+v;                    Put Edit(pp(w))(Skip,a);
 x=v-w;                    Put Edit(pp(x))(Skip,a);
 y=x*3;                    Put Edit(pp(y))(Skip,a);
 z=x/.1;                   Put Edit(pp(z))(Skip,a);

 pp: Proc(c) Returns(Char(50) Var);
 Dcl c Dec Float(9) Complex;
 Dcl res Char(50) Var;
 Put String(res) Edit('[',real(c),',',imag(c),']')
                     (3(a,f(9,5)));
 Return(res);
 End;
 End;


$V1 = New-Object System.Windows.Vector ( 2.5, 3.4 )
$V2 = New-Object System.Windows.Vector ( -6, 2 )
$V1
$V2
$V1 + $V2
$V1 - $V2
$V1 * 3
$V1 / 8


PVector v1 = new PVector(5, 7);
PVector v2 = new PVector(2, 3);

println(v1.x, v1.y, v1.mag(), v1.heading(),'\n');

// static methods
println(PVector.add(v1, v2));
println(PVector.sub(v1, v2));
println(PVector.mult(v1, 11));
println(PVector.div(v1, 2), '\n');

// object methods
println(v1.sub(v1));
println(v1.add(v2));
println(v1.mult(10));
println(v1.div(10));


class Vector:
    def __init__(self,m,value):
        self.m = m
        self.value = value
        self.angle = math.degrees(math.atan(self.m))
        self.x = self.value * math.sin(math.radians(self.angle))
        self.y = self.value * math.cos(math.radians(self.angle))

    def __add__(self,vector):
        """
        >>> Vector(1,10) + Vector(1,2)
        Vector:
            - Angular coefficient: 1.0
            - Angle: 45.0 degrees
            - Value: 12.0
            - X component: 8.49
            - Y component: 8.49
        """
        final_x = self.x + vector.x
        final_y = self.y + vector.y
        final_value = pytagoras(final_x,final_y)
        final_m = final_y / final_x
        return Vector(final_m,final_value)

    def __neg__(self):
        return Vector(self.m,-self.value)

    def __sub__(self,vector):
        return self + (- vector)

    def __mul__(self,scalar):
        """
        >>> Vector(4,5) * 2
        Vector:
            - Angular coefficient: 4
            - Angle: 75.96 degrees
            - Value: 10
            - X component: 9.7
            - Y component: 2.43

        """
        return Vector(self.m,self.value*scalar)

    def __div__(self,scalar):
        return self * (1 / scalar)

    def __repr__(self):
        """
        Returns a nicely formatted list of the properties of the Vector.

        >>> Vector(1,10)
        Vector:
            - Angular coefficient: 1
            - Angle: 45.0 degrees
            - Value: 10
            - X component: 7.07
            - Y component: 7.07

        """
        return """Vector:
    - Angular coefficient: {}
    - Angle: {} degrees
    - Value: {}
    - X component: {}
    - Y component: {}""".format(self.m.__round__(2),
               self.angle.__round__(2),
               self.value.__round__(2),
               self.x.__round__(2),
               self.y.__round__(2))


#lang racket

(require racket/flonum)

(define (rad->deg x) (fl* 180. (fl/ (exact->inexact x) pi)))

;Custom printer
;no shared internal structures
(define (vec-print v port mode)
  (write-string "Vec:\n" port)
  (write-string (format " -Slope: ~a\n" (vec-slope v)) port)
  (write-string (format " -Angle(deg): ~a\n" (rad->deg (vec-angle v))) port)
  (write-string (format " -Norm: ~a\n" (vec-norm v)) port)
  (write-string (format " -X: ~a\n" (vec-x v)) port)
  (write-string (format " -Y: ~a\n" (vec-y v)) port))

(struct vec (x y)
        #:methods gen:custom-write
        [(define write-proc vec-print)])

;Alternative constructor
(define (vec/slope-norm s n)
  (vec (* n (/ 1 (sqrt (+ 1 (sqr s)))))
       (* n (/ s (sqrt (+ 1 (sqr s)))))))

;Properties
(define (vec-norm v)
  (sqrt (+ (sqr (vec-x v)) (sqr (vec-y v)))))

(define (vec-slope v)
  (fl/ (exact->inexact (vec-y v)) (exact->inexact (vec-x v))))

(define (vec-angle v)
  (atan (vec-y v) (vec-x v)))

;Operations
(define (vec+ v w)
  (vec (+ (vec-x v) (vec-x w))
       (+ (vec-y v) (vec-y w))))

(define (vec- v w)
  (vec (- (vec-x v) (vec-x w))
       (- (vec-y v) (vec-y w))))

(define (vec*e v l)
  (vec (* (vec-x v) l)
       (* (vec-y v) l)))

(define (vec/e v l)
  (vec (/ (vec-x v) l)
       (/ (vec-y v) l)))


class Vector {
    has Real $.x;
    has Real $.y;

    multi submethod BUILD (:$!x!, :$!y!) {
        *
    }
    multi submethod BUILD (:$length!, :$angle!) {
        $!x = $length * cos $angle;
        $!y = $length * sin $angle;
    }
    multi submethod BUILD (:from([$x1, $y1])!, :to([$x2, $y2])!) {
        $!x = $x2 - $x1;
        $!y = $y2 - $y1;
    }

    method length { sqrt $.x ** 2 + $.y ** 2 }
    method angle  { atan2 $.y, $.x }

    method add      ($v) { Vector.new(x => $.x + $v.x,  y => $.y + $v.y) }
    method subtract ($v) { Vector.new(x => $.x - $v.x,  y => $.y - $v.y) }
    method multiply ($n) { Vector.new(x => $.x * $n,    y => $.y * $n  ) }
    method divide   ($n) { Vector.new(x => $.x / $n,    y => $.y / $n  ) }

    method gist { "vec[$.x, $.y]" }
}

multi infix:<+>  (Vector $v, Vector $w) is export { $v.add: $w }
multi infix:<->  (Vector $v, Vector $w) is export { $v.subtract: $w }
multi prefix:<-> (Vector $v)            is export { $v.multiply: -1 }
multi infix:<*>  (Vector $v, $n)        is export { $v.multiply: $n }
multi infix:</>  (Vector $v, $n)        is export { $v.divide: $n }

#####[ Usage example: ]#####

say my $u = Vector.new(x => 3, y => 4);                #: vec[3, 4]
say my $v = Vector.new(from => [1, 0], to => [2, 3]);  #: vec[1, 3]
say my $w = Vector.new(length => 1, angle => pi/4);    #: vec[0.707106781186548, 0.707106781186547]

say $u.length;                                         #: 5
say $u.angle * 180/pi;                                 #: 53.130102354156

say $u + $v;                                           #: vec[4, 7]
say $u - $v;                                           #: vec[2, 1]
say -$u;                                               #: vec[-3, -4]
say $u * 10;                                           #: vec[30, 40]
say $u / 2;                                            #: vec[1.5, 2]


Red [
	Source:     https://github.com/vazub/rosetta-red
	Tabs:       4
]

comment {
	Vector type is one of base datatypes in Red, with all arithmetic already implemented.

	Caveats to keep in mind:
	- Arithmetic on a single vector will modify the vector in place, so we use copy to avoid that
	- Division result on integer vectors will get truncated, use floats for decimal precision
}

v1: make vector! [5.0 7.0]
v2: make vector! [2.0 3.0]

prin pad "v1: " 10 print v1
prin pad "v2: " 10 print v2
prin pad "v1 + v2: " 10 print v1 + v2
prin pad "v1 - v2: " 10 print v1 - v2
prin pad "v1 * 11" 10 print (copy v1) * 11
prin pad "v1 / 2" 10 print (copy v1) / 2


/*REXX program shows how to support mathematical functions for vectors using functions. */
       s1 =     11                               /*define the  s1 scalar: eleven        */
       s2 =      2                               /*define the  s2 scalar: two           */
       x  = '(5, 7)'                             /*define the  X  vector: five and seven*/
       y  = '(2, 3)'                             /*define the  Y  vector: two  and three*/
       z  = '(2, 45)'                            /*define vector of length   2  at  45º */
call show  'define a vector (length,ºangle):',     z                ,      Vdef(z)
call show         'addition (vector+vector):',     x      " + "   y ,      Vadd(x, y)
call show      'subtraction (vector-vector):',     x      " - "   y ,      vsub(x, y)
call show   'multiplication (Vector*scalar):',     x      " * "   s1,      Vmul(x, s1)
call show         'division (vector/scalar):',     x      " ÷ "   s2,      Vdiv(x, s2)
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
$fuzz: return min( arg(1), max(1, digits() - arg(2) ) )
cosD:  return cos( d2r( arg(1) ) )
d2d:   return arg(1) // 360                      /*normalize degrees ──► a unit circle. */
d2r:   return r2r( d2d(arg(1)) * pi() / 180)     /*convert degrees   ──►   radians.     */
pi:    pi=3.14159265358979323846264338327950288419716939937510582;         return pi
r2d:   return d2d( (arg(1)*180 / pi()))          /*convert radians   ──►   degrees.     */
r2r:   return arg(1) // (pi() * 2)               /*normalize radians ──► a unit circle. */
show:  say  right( arg(1), 33)   right( arg(2), 20)      ' ──► '      arg(3);       return
sinD:  return  sin( d2r( d2d( arg(1) ) ) )
V:     return  word( translate( arg(1), , '{[(JI)]}')  0,  1)   /*get the number or zero*/
V$:    parse arg r,c;     _='['r;       if c\=0  then _=_"," c;               return _']'
V#:    a=V(a); b=V(b); c=V(c); d=V(d);  ac=a*c; ad=a*d; bc=b*c; bd=b*d; s=c*c+d*d;  return
Vadd:  procedure; arg a ',' b,c "," d;      call V#;       return V$(a+c,             b+d)
Vsub:  procedure; arg a ',' b,c "," d;      call V#;       return V$(a-c,             b-d)
Vmul:  procedure; arg a ',' b,c "," d;      call V#;       return V$(ac-bd,         bc+ad)
Vdiv:  procedure; arg a ',' b,c "," d;      call V#;       return V$((ac+bd)/s, (bc-ad)/s)
Vdef:  procedure; arg a ',' b,c "," d;      call V#;       return V$(a*sinD(b), a*cosD(b))
/*──────────────────────────────────────────────────────────────────────────────────────*/
cos: procedure; parse arg x;        x=r2r(x);       a=abs(x);    numeric fuzz $fuzz(9, 9)
                if a=pi             then return -1;
                if a=pi*.5 | a=pi*2 then return  0;                   return .sinCos(1,-1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
sin: procedure; parse arg x;        x=r2r(x);                    numeric fuzz $fuzz(5, 3)
                if x=pi*.5          then return 1;  if x=pi*1.5  then return -1
                if abs(x)=pi | x=0  then return 0;                    return .sinCos(x,+1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
.sinCos: parse arg z 1 _,i;          q=x*x
           do k=2  by 2  until p=z;  p=z;  _= -_*q / (k*(k+i));  z=z+_;  end;     return z


# Project : Vector

decimals(1)
vect1 = [5, 7]
vect2 = [2, 3]
vect3 = list(len(vect1))

for n = 1 to len(vect1)
    vect3[n] = vect1[n] + vect2[n]
next
showarray(vect3)

for n = 1 to len(vect1)
    vect3[n] = vect1[n] - vect2[n]
next
showarray(vect3)

for n = 1 to len(vect1)
    vect3[n] = vect1[n] * vect2[n]
next
showarray(vect3)

for n = 1 to len(vect1)
    vect3[n] = vect1[n] / 2
next
showarray(vect3)

func showarray(vect3)
     see "["
     svect = ""
     for n = 1 to len(vect3)
         svect = svect + vect3[n] + ", "
     next
     svect = left(svect, len(svect) - 2)
     see svect
     see "]" + nl


class Vector
  def self.polar(r, angle=0)
    new(r*Math.cos(angle), r*Math.sin(angle))
  end

  attr_reader :x, :y

  def initialize(x, y)
    raise TypeError unless x.is_a?(Numeric) and y.is_a?(Numeric)
    @x, @y = x, y
  end

  def +(other)
    raise TypeError if self.class != other.class
    self.class.new(@x + other.x, @y + other.y)
  end

  def -@;       self.class.new(-@x, -@y)        end
  def -(other)  self + (-other)                 end

  def *(scalar)
    raise TypeError unless scalar.is_a?(Numeric)
    self.class.new(@x * scalar, @y * scalar)
  end

  def /(scalar)
    raise TypeError unless scalar.is_a?(Numeric) and scalar.nonzero?
    self.class.new(@x / scalar, @y / scalar)
  end

  def r;        @r     ||= Math.hypot(@x, @y)   end
  def angle;    @angle ||= Math.atan2(@y, @x)   end
  def polar;    [r, angle]                      end
  def rect;     [@x, @y]                        end
  def to_s;     "#{self.class}#{[@x, @y]}"      end
  alias inspect to_s
end

p v = Vector.new(1,1)                   #=> Vector[1, 1]
p w = Vector.new(3,4)                   #=> Vector[3, 4]
p v + w                                 #=> Vector[4, 5]
p v - w                                 #=> Vector[-2, -3]
p -v                                    #=> Vector[-1, -1]
p w * 5                                 #=> Vector[15, 20]
p w / 2.0                               #=> Vector[1.5, 2.0]
p w.x                                   #=> 3
p w.y                                   #=> 4
p v.polar                               #=> [1.4142135623730951, 0.7853981633974483]
p w.polar                               #=> [5.0, 0.9272952180016122]
p z = Vector.polar(1, Math::PI/2)       #=> Vector[6.123031769111886e-17, 1.0]
p z.rect                                #=> [6.123031769111886e-17, 1.0]
p z.polar                               #=> [1.0, 1.5707963267948966]
p z = Vector.polar(-2, Math::PI/4)      #=> Vector[-1.4142135623730951, -1.414213562373095]
p z.polar                               #=> [2.0, -2.356194490192345]


use std::fmt;
use std::ops::{Add, Div, Mul, Sub};

#[derive(Copy, Clone, Debug)]
pub struct Vector<T> {
    pub x: T,
    pub y: T,
}

impl<T> fmt::Display for Vector<T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(prec) = f.precision() {
            write!(f, "[{:.*}, {:.*}]", prec, self.x, prec, self.y)
        } else {
            write!(f, "[{}, {}]", self.x, self.y)
        }
    }
}

impl<T> Vector<T> {
    pub fn new(x: T, y: T) -> Self {
        Vector { x, y }
    }
}

impl Vector<f64> {
    pub fn from_polar(r: f64, theta: f64) -> Self {
        Vector {
            x: r * theta.cos(),
            y: r * theta.sin(),
        }
    }
}

impl<T> Add for Vector<T>
where
    T: Add<Output = T>,
{
    type Output = Self;

    fn add(self, other: Self) -> Self::Output {
        Vector {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

impl<T> Sub for Vector<T>
where
    T: Sub<Output = T>,
{
    type Output = Self;

    fn sub(self, other: Self) -> Self::Output {
        Vector {
            x: self.x - other.x,
            y: self.y - other.y,
        }
    }
}

impl<T> Mul<T> for Vector<T>
where
    T: Mul<Output = T> + Copy,
{
    type Output = Self;

    fn mul(self, scalar: T) -> Self::Output {
        Vector {
            x: self.x * scalar,
            y: self.y * scalar,
        }
    }
}

impl<T> Div<T> for Vector<T>
where
    T: Div<Output = T> + Copy,
{
    type Output = Self;

    fn div(self, scalar: T) -> Self::Output {
        Vector {
            x: self.x / scalar,
            y: self.y / scalar,
        }
    }
}

fn main() {
    use std::f64::consts::FRAC_PI_3;

    println!("{:?}", Vector::new(4, 5));
    println!("{:.4}", Vector::from_polar(3.0, FRAC_PI_3));
    println!("{}", Vector::new(2, 3) + Vector::new(4, 6));
    println!("{:.4}", Vector::new(5.6, 1.3) - Vector::new(4.2, 6.1));
    println!("{:.4}", Vector::new(3.0, 4.2) * 2.3);
    println!("{:.4}", Vector::new(3.0, 4.2) / 2.3);
    println!("{}", Vector::new(3, 4) / 2);
}


object Vector extends App {

  case class Vector2D(x: Double, y: Double) {
    def +(v: Vector2D) = Vector2D(x + v.x, y + v.y)

    def -(v: Vector2D) = Vector2D(x - v.x, y - v.y)

    def *(s: Double) = Vector2D(s * x, s * y)

    def /(s: Double) = Vector2D(x / s, y / s)

    override def toString() = s"Vector($x, $y)"
  }

  val v1 = Vector2D(5.0, 7.0)
  val v2 = Vector2D(2.0, 3.0)
  println(s"v1 = $v1")
  println(s"v2 = $v2\n")

  println(s"v1 + v2 = ${v1 + v2}")
  println(s"v1 - v2 = ${v1 - v2}")
  println(s"v1 * 11 = ${v1 * 11.0}")
  println(s"11 * v2 = ${v2 * 11.0}")
  println(s"v1 / 2  = ${v1 / 2.0}")

  println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
}


class MyVector(:args) {

    has Number x
    has Number y

    method init {
        if ([:x, :y] ~~ args) {
            x = args{:x}
            y = args{:y}
        }
        elsif ([:length, :angle] ~~ args) {
            x = args{:length}*args{:angle}.cos
            y = args{:length}*args{:angle}.sin
        }
        elsif ([:from, :to] ~~ args) {
            x = args{:to}[0]-args{:from}[0]
            y = args{:to}[1]-args{:from}[1]
        }
        else {
            die "Invalid arguments: #{args}"
        }
    }

    method length { hypot(x, y) }
    method angle  { atan2(y, x) }

    method +(MyVector v) { MyVector(x => x + v.x,  y => y + v.y) }
    method -(MyVector v) { MyVector(x => x - v.x,  y => y - v.y) }
    method *(Number n)   { MyVector(x => x * n,    y => y * n)   }
    method /(Number n)   { MyVector(x => x / n,    y => y / n)   }

    method neg  { self * -1 }
    method to_s { "vec[#{x}, #{y}]" }
}

var u = MyVector(x => 3, y => 4)
var v = MyVector(from => [1, 0], to => [2, 3])
var w = MyVector(length => 1, angle => 45.deg2rad)

say u    #: vec[3, 4]
say v    #: vec[1, 3]
say w    #: vec[0.70710678118654752440084436210485, 0.70710678118654752440084436210485]

say u.length                             #: 5
say u.angle.rad2deg                      #: 53.13010235415597870314438744090659

say u+v                                  #: vec[4, 7]
say u-v                                  #: vec[2, 1]
say -u                                   #: vec[-3, -4]
say u*10                                 #: vec[30, 40]
say u/2                                  #: vec[1.5, 2]


import Foundation
#if canImport(Numerics)
import Numerics
#endif

struct Vector<T: Numeric> {
  var x: T
  var y: T

  func prettyPrinted(precision: Int = 4) -> String where T: CVarArg & FloatingPoint {
    return String(format: "[%.\(precision)f, %.\(precision)f]", x, y)
  }

  static func +(lhs: Vector, rhs: Vector) -> Vector {
    return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
  }

  static func -(lhs: Vector, rhs: Vector) -> Vector {
    return Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
  }

  static func *(lhs: Vector, scalar: T) -> Vector {
    return Vector(x: lhs.x * scalar, y: lhs.y * scalar)
  }

  static func /(lhs: Vector, scalar: T) -> Vector where T: FloatingPoint {
    return Vector(x: lhs.x / scalar, y: lhs.y / scalar)
  }

  static func /(lhs: Vector, scalar: T) -> Vector where T: BinaryInteger {
    return Vector(x: lhs.x / scalar, y: lhs.y / scalar)
  }
}

#if canImport(Numerics)
extension Vector where T: ElementaryFunctions {
  static func fromPolar(radians: T, theta: T) -> Vector {
    return Vector(x: radians * T.cos(theta), y: radians * T.sin(theta))
  }
}
#else
extension Vector where T == Double {
  static func fromPolar(radians: Double, theta: Double) -> Vector {
    return Vector(x: radians * cos(theta), y: radians * sin(theta))
  }
}
#endif

print(Vector(x: 4, y: 5))
print(Vector.fromPolar(radians: 3.0, theta: .pi / 3).prettyPrinted())
print((Vector(x: 2, y: 3) + Vector(x: 4, y: 6)))
print((Vector(x: 5.6, y: 1.3) - Vector(x: 4.2, y: 6.1)).prettyPrinted())
print((Vector(x: 3.0, y: 4.2) * 2.3).prettyPrinted())
print((Vector(x: 3.0, y: 4.2) / 2.3).prettyPrinted())
print(Vector(x: 3, y: 4) / 2)


namespace path ::tcl::mathop
proc vec {op a b} {
    if {[llength $a] == 1 && [llength $b] == 1} {
        $op $a $b
    } elseif {[llength $a]==1} {
        lmap i $b {vec $op $a $i}
    } elseif {[llength $b]==1} {
        lmap i $a {vec $op $i $b}
    } elseif {[llength $a] == [llength $b]} {
        lmap i $a j $b {vec $op $i $j}
    } else {error "length mismatch [llength $a] != [llength $b]"}
}

proc polar {r t} {
    list [expr {$r * cos($t)}] [expr {$r * sin($t)}]
}

proc check {cmd res} {
    set r [uplevel 1 $cmd]
    if {$r eq $res} {
        puts "Ok! $cmd \t = $res"
    } else {
        puts "ERROR: $cmd = $r \t expected $res"
    }
}

check {vec + {5 7} {2 3}}   {7 10}
check {vec - {5 7} {2 3}}   {3 4}
check {vec * {5 7} 11}      {55 77}
check {vec / {5 7} 2.0}     {2.5 3.5}
check {polar 2 0.785398}    {1.41421 1.41421}


Type vector
    x As Double
    y As Double
End Type
Type vector2
    phi As Double
    r As Double
End Type
Private Function vector_addition(u As vector, v As vector) As vector
    vector_addition.x = u.x + v.x
    vector_addition.y = u.y + v.y
End Function
Private Function vector_subtraction(u As vector, v As vector) As vector
    vector_subtraction.x = u.x - v.x
    vector_subtraction.y = u.y - v.y
End Function
Private Function scalar_multiplication(u As vector, v As Double) As vector
    scalar_multiplication.x = u.x * v
    scalar_multiplication.y = u.y * v
End Function
Private Function scalar_division(u As vector, v As Double) As vector
    scalar_division.x = u.x / v
    scalar_division.y = u.y / v
End Function
Private Function to_cart(v2 As vector2) As vector
    to_cart.x = v2.r * Cos(v2.phi)
    to_cart.y = v2.r * Sin(v2.phi)
End Function
Private Sub display(u As vector)
    Debug.Print "( " & Format(u.x, "0.000") & "; " & Format(u.y, "0.000") & ")";
End Sub
Public Sub main()
    Dim a As vector, b As vector, c As vector2, d As Double
    c.phi = WorksheetFunction.Pi() / 3
    c.r = 5
    d = 10
    a = to_cart(c)
    b.x = 1: b.y = -2
    Debug.Print "addition             : ";: display a: Debug.Print "+";: display b
    Debug.Print "=";: display vector_addition(a, b): Debug.Print
    Debug.Print "subtraction          : ";: display a: Debug.Print "-";: display b
    Debug.Print "=";: display vector_subtraction(a, b): Debug.Print
    Debug.Print "scalar multiplication: ";: display a: Debug.Print " *";: Debug.Print d;
    Debug.Print "=";: display scalar_multiplication(a, d): Debug.Print
    Debug.Print "scalar division      : ";: display a: Debug.Print " /";: Debug.Print d;
    Debug.Print "=";: display scalar_division(a, d)
End Sub


Module Module1

    Class Vector
        Public store As Double()

        Public Sub New(init As IEnumerable(Of Double))
            store = init.ToArray()
        End Sub

        Public Sub New(x As Double, y As Double)
            store = {x, y}
        End Sub

        Public Overloads Shared Operator +(v1 As Vector, v2 As Vector)
            Return New Vector(v1.store.Zip(v2.store, Function(a, b) a + b))
        End Operator

        Public Overloads Shared Operator -(v1 As Vector, v2 As Vector)
            Return New Vector(v1.store.Zip(v2.store, Function(a, b) a - b))
        End Operator

        Public Overloads Shared Operator *(v1 As Vector, scalar As Double)
            Return New Vector(v1.store.Select(Function(x) x * scalar))
        End Operator

        Public Overloads Shared Operator /(v1 As Vector, scalar As Double)
            Return New Vector(v1.store.Select(Function(x) x / scalar))
        End Operator

        Public Overrides Function ToString() As String
            Return String.Format("[{0}]", String.Join(",", store))
        End Function
    End Class

    Sub Main()
        Dim v1 As New Vector(5, 7)
        Dim v2 As New Vector(2, 3)
        Console.WriteLine(v1 + v2)
        Console.WriteLine(v1 - v2)
        Console.WriteLine(v1 * 11)
        Console.WriteLine(v1 / 2)
        ' Works with arbitrary size vectors, too.
        Dim lostVector As New Vector({4, 8, 15, 16, 23, 42})
        Console.WriteLine(lostVector * 7)
    End Sub

End Module


let a => import 'arrays';
let s => import 'stream';

let vmath f v1 v2 =>
    s.zip (a.stream v1) (a.stream v2)
    -> s.map (@ m v =>
        let [v1 v2] => v;
        f (v1 { == s.end => 0 }) (v2 { == s.end => 0 });
    )
    -> s.collect
    ;

let smath f scalar vector => a.stream vector -> s.map (f scalar) -> s.collect;

let v+ => vmath +;
let v- => vmath -;

let s* => smath *;
let s/ => smath /;


class Vector2D {
    construct new(x, y) {
        _x = x
        _y = y
    }

    static fromPolar(r, theta) { new(r * theta.cos, r * theta.sin) }

    x { _x }
    y { _y }

    +(v) { Vector2D.new(_x + v.x, _y + v.y) }
    -(v) { Vector2D.new(_x - v.x, _y - v.y) }
    *(s) { Vector2D.new(_x * s,   _y * s) }
    /(s) { Vector2D.new(_x / s,   _y / s) }

    toString { "(%(_x), %(_y))" }
}

var times = Fn.new { |d, v| v * d }

var v1 = Vector2D.new(5, 7)
var v2 = Vector2D.new(2, 3)
var v3 = Vector2D.fromPolar(2.sqrt, Num.pi / 4)
System.print("v1 = %(v1)")
System.print("v2 = %(v2)")
System.print("v3 = %(v3)")
System.print()
System.print("v1 + v2 = %(v1 + v2)")
System.print("v1 - v2 = %(v1 - v2)")
System.print("v1 * 11 = %(v1 * 11)")
System.print("11 * v2 = %(times.call(11, v2))")
System.print("v1 / 2  = %(v1 /  2)")


dim vect1(2)
vect1(1) = 5 : vect1(2) = 7
dim vect2(2)
vect2(1) = 2 : vect2(2) = 3
dim vect3(arraysize(vect1(),1))

for n = 1 to arraysize(vect1(),1)
    vect3(n) = vect1(n) + vect2(n)
next n
print "[", vect1(1), ", ", vect1(2), "] + [", vect2(1), ", ", vect2(2), "] = ";
showarray(vect3)

for n = 1 to arraysize(vect1(),1)
    vect3(n) = vect1(n) - vect2(n)
next n
print "[", vect1(1), ", ", vect1(2), "] - [", vect2(1), ", ", vect2(2), "] = ";
showarray(vect3)

for n = 1 to arraysize(vect1(),1)
    vect3(n) = vect1(n) * 11
next n
print "[", vect1(1), ", ", vect1(2), "] * ", 11, "     = ";
showarray(vect3)

for n = 1 to arraysize(vect1(),1)
    vect3(n) = vect1(n) / 2
next n
print "[", vect1(1), ", ", vect1(2), "] / ", 2, "      = ";
showarray(vect3)
end

sub showarray(vect3)
    print "[";
    svect$ = ""
    for n = 1 to arraysize(vect3(),1)
        svect$ = svect$ + str$(vect3(n)) + ", "
    next n
    svect$ = left$(svect$, len(svect$) - 2)
    print svect$;
    print "]"
end sub


class Vector{
   var length,angle;  // polar coordinates, radians
   fcn init(length,angle){  // angle in degrees
      self.length,self.angle = vm.arglist.apply("toFloat");
      self.angle=self.angle.toRad();
   }
   fcn toXY{ length.toRectangular(angle) }
   // math is done in place
   fcn __opAdd(vector){
      x1,y1:=toXY(); x2,y2:=vector.toXY();
      length,angle=(x1+x2).toPolar(y1+y2);
      self
   }
   fcn __opSub(vector){
      x1,y1:=toXY(); x2,y2:=vector.toXY();
      length,angle=(x1-x2).toPolar(y1-y2);
      self
   }
   fcn __opMul(len){ length*=len; self }
   fcn __opDiv(len){ length/=len; self }
   fcn print(msg=""){
#<<<
"Vector%s:
   Length: %f
   Angle:  %f\Ub0;
   X: %f
   Y: %f"
#<<<
      .fmt(msg,length,angle.toDeg(),length.toRectangular(angle).xplode())
      .println();
   }
   fcn toString{ "Vector(%f,%f\Ub0;)".fmt(length,angle.toDeg()) }
}


F van_eck(c)
   [Int] r
   V n = 0
   V seen = [0]
   V val = 0
   L
      r.append(val)
      I r.len == c
         R r
      I val C seen[1..]
         val = seen.index(val, 1)
      E
         val = 0
      seen.insert(0, val)
      n++

print(‘Van Eck: first 10 terms:   ’van_eck(10))
print(‘Van Eck: terms 991 - 1000: ’van_eck(1000)[(len)-10..])


	org	100h
	lxi	h,ecks	; Zero out 2000 bytes
	lxi	b,0
	lxi	d,2000
zero:	mov	m,b
	inx	h
	dcx	d
	mov	a,d
	ora	e
	jnz 	zero
	lxi	b,-1	; BC = Outer loop variable
outer:	inx	b
	mvi	a,3	; Are we there yet? 1000 = 03E8h
	cmp	b	; Compare high byte
	jnz	go
	mvi	a,0E8h	; Compare low byte
	cmp	c
	jz	done
go:	mov	d,b	; DE = Inner loop variable
	mov	e,c
inner:	dcx	d
	mov	a,d	; <= 0?
	ral
	jc	outer
	push	b	; Keep both pointers
	push	d
	mov	h,b	; Load BC = eck[BC]
	mov	l,c
	call	eck
	mov	c,m
	inx	h
	mov	b,m
	xchg		; Load HL = -eck[DE]
	call	eck
	xchg
	ldax 	d
	cma
	mov	l,a
	inx	d
	ldax 	d
	cma
	mov	h,a
	inx	h 	; Two's complement
	dad	b	; -eck[DE] + eck[BC]
	mov	a,h	; Unfortunately this does not set flags
	ora	l	; Check zero
	pop	d	; Meanwhile, restore the pointers
	pop	b
	jnz	inner	; If no match, continue with inner loop
	mov	h,b	; If we _did_, then get &eck[BC + 1]
	mov	l,c
	inx	h
	call 	eck
	mov	a,c	; Store BC - DE at that address
	sub	e
	mov	m,a
	inx	h
	mov	a,b
	sbb	d
	mov	m,a
	jmp 	outer	; And continue the outer loop
done:	lxi	h,0	; Print first 10 terms
	call	p10
	lxi	h,990	; Print last 10 terms
p10:	mvi 	b,10	; Print 10 terms starting at term HL
	call	eck
ploop:	mov	e,m	; Load term into DE
	inx	h
	mov	d,m
	inx	h
	push 	b	; Keep counter
	push 	h	; Keep pointer
	xchg		; Term in HL
	call	printn	; Print term
	pop 	h	; Restore pointer and counter
	pop 	b
	dcr	b
	jnz	ploop
	lxi	d,nl	; Print a newline afterwards
	jmp	prints
eck:	push	b	; Set HL = &eck[HL]
	lxi	b,ecks	; Base address
	dad	h	; Multiply by two
	dad	b	; Add base
	pop	b
	ret
printn:	lxi	d,buf	; Print the number in HL
	push	d	; Buffer pointer on stack
	lxi	b,-10	; Divisor
pdigit:	lxi	d,-1	; Quotient
pdiv:	inx 	d
	dad	b
	jc 	pdiv
	mvi	a,'0'+10
	add	l	; Make ASCII digit
	pop	h
	dcx	h	; Store digit
	mov	m,a
	push 	h
	xchg
	mov	a,h	; Quotient nonzero?
	ora	l
	jnz	pdigit	; Then there are more digits
	pop	d 	; Otherwise, print string using CP/M
prints:	mvi	c,9
	jmp	5
nl:	db	13,10,'$'
	db	'.....'
buf:	db	' $'
ecks:	equ	$


LIMIT:	equ	1000
	cpu	8086
	org	100h
section	.text
	mov	di,eck		; Zero out the memory
	xor	ax,ax
	mov	cx,LIMIT
	rep	stosw
	mov	bx,eck		; Base address
	mov	cx,LIMIT	; Limit
	xor	ax,ax
	mov	si,-1		; Outer loop index
outer:	inc	si
	dec	cx
	jcxz	done
	mov	di,si		; Inner loop index
inner:	dec	di
	js	outer
	shl	si,1		; Shift the loop indices (each entry is 2 bytes)
	shl	di,1
	mov	ax,[si+bx]	; Find a match?
	cmp	ax,[di+bx]
	je	match
	shr	si,1		; If not, shift SI and DI back and keep going
	shr	di,1
	jmp	inner
match:	mov	ax,si		; Calculate the new value
	sub	ax,di
	shr	ax,1		; Compensate for shift
	mov	[si+bx+2],ax	; Store value
	shr	si,1		; Shift SI back and calculate next value
	jmp	outer
done:	xor	si,si		; Print first 10 elements
	call	p10
	mov	si,LIMIT-10	; Print last 10 elements⌈
p10:	mov	cx,10		; Print 10 elements starting at SI
	shl	si,1		; Items are 2 bytes wide
	add	si,eck
.item:	lodsw			; Retrieve item
	call	printn		; Print it
	loop	.item
	mov	dx,nl		; Print a newline afterwards
	jmp	prints
printn:	mov	bx,buf		; Print AX
	mov	bp,10
.digit:	xor	dx,dx		; Extract digit
	div	bp
	add	dl,'0'		; ASCII digit
	dec	bx
	mov	[bx],dl		; Store in buffer
	test	ax,ax		; Any more digits?
	jnz	.digit
	mov	dx,bx
prints:	mov	ah,9		; Print string in buffer
	int	21h
	ret
section	.data
nl:	db	13,10,'$'
	db	'.....'
buf:	db	' $'
section	.bss
eck:	resw	LIMIT


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

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

.equ MAXI,      1000

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResultElement:    .asciz " @ "
szCarriageReturn:   .asciz "\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:                  .skip 24
TableVanEck:                .skip 8 * MAXI
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                             // entry of program
    mov x2,#0                     // begin first element
    mov x3,#0                     // current counter
    ldr x4,qAdrTableVanEck        // table address
    str x2,[x4,x3,lsl 3]          // store first zéro
1:                                // begin loop
    mov x5,x3                     // init current indice
2:
    sub x5,x5,1                   // decrement
    cmp x5,0                      // end table ?
    blt 3f
    ldr x6,[x4,x5,lsl 3]          // load element
    cmp x6,x2                     // and compare with the last element
    bne 2b                        // not equal
    sub x2,x3,x5                  // else compute gap
    b 4f
3:
    mov x2,#0                     // first, move zero to next element
4:
    add x3,x3,#1                  // increment counter
    str x2,[x4,x3,lsl 3]          // and store new element
    cmp x3,MAXI
    blt 1b

    mov x2,0
5:                                // loop display ten elements
    ldr x0,[x4,x2,lsl 3]
    ldr x1,qAdrsZoneConv
    bl conversion10               // call décimal conversion
    ldr x0,qAdrsMessResultElement
    ldr x1,qAdrsZoneConv          // insert conversion in message
    bl strInsertAtCharInc
    mov x1,0                      // final zéro
    strb w1,[x0,5]                //
    bl affichageMess              // display message
    add x2,x2,1                   // increment indice
    cmp x2,10                     // end ?
    blt 5b                        // no -> loop
    ldr x0,qAdrszCarriageReturn
    bl affichageMess

    mov x2,MAXI - 10
6:                                // loop display ten elements 990-999
    ldr x0,[x4,x2,lsl 3]
    ldr x1,qAdrsZoneConv
    bl conversion10               // call décimal conversion
    ldr x0,qAdrsMessResultElement
    ldr x1,qAdrsZoneConv          // insert conversion in message
    bl strInsertAtCharInc
    mov x1,0                      // final zéro
    strb w1,[x0,5]                //
    bl affichageMess              // display message
    add x2,x2,1                   // increment indice
    cmp x2,MAXI                   // end ?
    blt 6b                        // no -> loop
    ldr x0,qAdrszCarriageReturn
    bl affichageMess

100:                              // standard end of the program
    mov x0, 0                     // return code
    mov x8, EXIT                  // request to exit program
    svc 0                         // perform the system call
qAdrszCarriageReturn:    .quad szCarriageReturn
qAdrsMessResultElement:  .quad sMessResultElement
qAdrsZoneConv:           .quad sZoneConv
qAdrTableVanEck:         .quad TableVanEck
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


INT FUNC LastPos(INT ARRAY a INT count,value)
  INT pos

  pos=count-1
  WHILE pos>=0 AND a(pos)#value
  DO
    pos==-1
  OD
RETURN (pos)

PROC Main()
  DEFINE MAX="1000"
  INT ARRAY seq(MAX)
  INT i,pos

  seq(0)=0
  FOR i=1 TO MAX-1
  DO
    pos=LastPos(seq,i-1,seq(i-1))
    IF pos>=0 THEN
      seq(i)=i-1-pos
    ELSE
      seq(i)=0
    FI
  OD

  PrintE("Van Eck first 10 terms:")
  FOR i=0 TO 9
  DO
    PrintI(seq(i)) Put(32)
  OD
  PutE() PutE()

  PrintE("Van Eck terms 991-1000:")
  FOR i=990 TO 999
  DO
    PrintI(seq(i)) Put(32)
  OD
RETURN


with Ada.Text_IO;

procedure Van_Eck_Sequence is

   Sequence : array (Natural range 1 .. 1_000) of Natural;

   procedure Calculate_Sequence is
   begin
      Sequence (Sequence'First) := 0;
      for Index in Sequence'First .. Sequence'Last - 1 loop
         Sequence (Index + 1) := 0;
         for I in reverse Sequence'First .. Index - 1 loop
            if Sequence (I) = Sequence (Index) then
               Sequence (Index + 1) := Index - I;
               exit;
            end if;
         end loop;
      end loop;
   end Calculate_Sequence;

   procedure Show (First, Last : in Positive) is
      use Ada.Text_IO;
   begin
      Put ("Element" & First'Image & " .." & Last'Image & " of Van Eck sequence: ");
      for I in First .. Last loop
         Put (Sequence (I)'Image);
      end loop;
      New_Line;
   end Show;

begin
   Calculate_Sequence;
   Show (First =>   1, Last =>    10);
   Show (First => 991, Last => 1_000);
end Van_Eck_Sequence;


BEGIN # find elements of the Van Eck Sequence - first term is 0, following  #
      # terms are 0 if the previous was the first appearance of the element #
      #        or how far back in the sequence the last element appeared    #
    # returns the first n elements of the Van Eck sequence                  #
    OP VANECK = ( INT n )[]INT:
       BEGIN
            [ 1 : IF n < 0 THEN 0 ELSE n FI ]INT result; FOR i TO n DO result[ i ] := 0 OD;
            [ 0 : UPB result ]INT pos;  FOR i FROM 0 TO n DO pos[ i ] := 0 OD;
            FOR i FROM 2 TO n DO
                INT j    = i - 1;
                INT prev = result[ j ];
                IF pos[ prev ] /= 0 THEN
                    # not a new element                                     #
                    result[ i ] := j - pos[ prev ]
                FI;
                pos[ prev ] := j
            OD;
            result
       END # VANECK # ;
    # construct the first 1000 terms of the sequence                        #
    []INT seq = VANECK 1000;
    # show the first and last 10 elements                                   #
    FOR i TO 10 DO print( ( " ", whole( seq[ i ], 0 ) ) ) OD;
    print( ( newline ) );
    FOR i FROM UPB seq - 9 TO UPB seq DO print( ( " ", whole( seq[ i ], 0 ) ) ) OD;
    print( ( newline ) )
END


begin
integer array eck[1:1000];
integer i, j;

for i := 1 step 1 until 1000 do
    eck[i] := 0;

for i := 1 step 1 until 999 do
begin
    j := i - 1;
    while j > 0 and eck[i] <> eck[j] do
        j := j - 1;
    if j <> 0 then
        eck[i+1] := i - j;
end;

for i := 1 step 1 until 10 do
    writeon(eck[i]);
write("");
for i := 991 step 1 until 1000 do
    writeon(eck[i]);

end


begin % find elements of the Van Eck Sequence - first term is 0, following  %
      % terms are 0 if the previous was the first appearance of the element %
      %        or how far back in the sequence the last element appeared    %
    % sets s to the first n elements of the Van Eck sequence                %
    procedure VanEck ( integer array s ( * ) ; integer value n ) ;
    begin
        integer array pos ( 0 :: n );
        for i := 1 until n do s(   i ) := 0;
        for i := 0 until n do pos( i ) := 0;
        for i := 2 until n do begin
            integer j, prev;
            j    := i - 1;
            prev := s( j );
            if pos( prev ) not = 0 then begin
                    % not a new element                                     %
                    s( i ) := j - pos( prev )
            end if_pos_prev_ne_0 ;
            pos( prev ) := j
        end for_j;
    end VanEck ;
    % construct the first 1000 terms of the sequence                        %
    integer MAX_VAN_ECK;
    MAX_VAN_ECK := 1000;
    begin
        integer array seq ( 1 :: MAX_VAN_ECK );
        VanEck( seq, MAX_VAN_ECK );
        % show the first and last 10 elements                               %
        for i := 1 until 10 do writeon( i_w := 1, s_w := 0, " ", seq( i ) );
        write();
        for i := MAX_VAN_ECK - 9 until MAX_VAN_ECK do writeon( i_w := 1, s_w := 0, " ", seq( i ) );
        write()
    end
end.


use AppleScript version "2.4"
use scripting additions

-- vanEck :: Int -> [Int]
on vanEck(n)
    -- First n terms of the vanEck sequence.

    script go
        on |λ|(xns, i)
            set {x, ns} to xns
            set prev to item (1 + x) of ns

            if 0 ≠ prev then
                set v to i - prev
            else
                set v to 0
            end if

            {{v, insert(ns, x, i)}, v}
        end |λ|
    end script

    {0} & item 2 of mapAccumL(go, ¬
        {0, replicate(n, 0)}, enumFromTo(1, n - 1))
end vanEck

--------------------------- TEST ---------------------------
on run
    unlines({¬
        "First 10 terms:", ¬
        showList(vanEck(10)), ¬
        "", ¬
        "Terms 990 to 1000:", ¬
        showList(items -10 thru -1 of vanEck(1000))})
end run

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

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m ≤ n then
        set lst to {}
        repeat with i from m to n
            set end of lst to i
        end repeat
        lst
    else
        {}
    end if
end enumFromTo

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

-- insert :: [Int] -> Int -> Int -> [Int]
on insert(xs, i, v)
    -- A list updated at position i with value v.
    set item (1 + i) of xs to v
    xs
end insert

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

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

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

-- 'The mapAccumL function behaves like a combination of map and foldl;
-- it applies a function to each element of a list, passing an
-- accumulating parameter from |Left| to |Right|, and returning a final
-- value of this accumulator together with the new list.' (see Hoogle)
-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
on mapAccumL(f, acc, xs)
    script
        on |λ|(a, x, i)
            tell mReturn(f) to set pair to |λ|(item 1 of a, x, i)
            {item 1 of pair, (item 2 of a) & {item 2 of pair}}
        end |λ|
    end script

    foldl(result, {acc, []}, xs)
end mapAccumL

-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
    set out to {}
    if 1 > n then return out
    set dbl to {a}

    repeat while (1 < n)
        if 0 < (n mod 2) then set out to out & dbl
        set n to (n div 2)
        set dbl to (dbl & dbl)
    end repeat
    return out & dbl
end replicate

-- showList :: [a] -> String
on showList(xs)
    "[" & intercalate(", ", map(my str, xs)) & "]"
end showList

-- str :: a -> String
on str(x)
    x as string
end str

-- unlines :: [String] -> String
on unlines(xs)
    -- A single string formed by the intercalation
    -- of a list of strings with the newline character.
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, linefeed}
    set s to xs as text
    set my text item delimiters to dlm
    s
end unlines


/* ARM assembly Raspberry PI  */
/*  program vanEckSerie.s   */

 /* REMARK 1 : this program use routines in a include file
   see task Include a file language arm assembly
   for the routine affichageMess conversion10
   see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes                       */
/************************************/
.include "../constantes.inc"

.equ MAXI,      1000

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResultElement:    .asciz " @ "
szCarriageReturn:   .asciz "\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:                  .skip 24
TableVanEck:                .skip 4 * MAXI
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                             @ entry of program
    mov r2,#0                     @ begin first element
    mov r3,#0                     @ current counter
    ldr r4,iAdrTableVanEck        @ table address
    str r2,[r4,r3,lsl #2]         @ store first zéro
1:                                @ begin loop
    mov r5,r3                     @ init current indice
2:
    sub r5,#1                     @ decrement
    cmp r5,#0                     @ end table ?
    movlt r2,#0                   @ yes, move zero to next element
    blt 3f
    ldr r6,[r4,r5,lsl #2]         @ load element
    cmp r6,r2                     @ and compare with the last element
    bne 2b                        @ not equal
    sub r2,r3,r5                  @ else compute gap
3:
    add r3,r3,#1                  @ increment counter
    str r2,[r4,r3,lsl #2]         @ and store new element
    cmp r3,#MAXI
    blt 1b

    mov r2,#0
4:                                @ loop display ten elements
    ldr r0,[r4,r2,lsl #2]
    ldr r1,iAdrsZoneConv
    bl conversion10               @ call décimal conversion
    ldr r0,iAdrsMessResultElement
    ldr r1,iAdrsZoneConv          @ insert conversion in message
    bl strInsertAtCharInc
    mov r1,#0                     @ final zéro
    strb r1,[r0,#5]               @
    bl affichageMess              @ display message
    add r2,#1                     @ increment indice
    cmp r2,#10                    @ end ?
    blt 4b                        @ no -> loop
    ldr r0,iAdrszCarriageReturn
    bl affichageMess

    mov r2,#MAXI - 10
5:                                @ loop display ten elements 990-999
    ldr r0,[r4,r2,lsl #2]
    ldr r1,iAdrsZoneConv
    bl conversion10               @ call décimal conversion
    ldr r0,iAdrsMessResultElement
    ldr r1,iAdrsZoneConv          @ insert conversion in message
    bl strInsertAtCharInc
    mov r1,#0                     @ final zéro
    strb r1,[r0,#5]               @
    bl affichageMess              @ display message
    add r2,#1                     @ increment indice
    cmp r2,#MAXI                    @ end ?
    blt 5b                        @ no -> loop
    ldr r0,iAdrszCarriageReturn
    bl affichageMess

100:                              @ standard end of the program
    mov r0, #0                    @ return code
    mov r7, #EXIT                 @ request to exit program
    svc #0                        @ perform the system call
iAdrszCarriageReturn:    .int szCarriageReturn
iAdrsMessResultElement:  .int sMessResultElement
iAdrsZoneConv:           .int sZoneConv
iAdrTableVanEck:         .int TableVanEck

/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
.include "../affichage.inc"


Max: 1000
a: array.of: Max 0

loop 0..Max-2 'n [
    if 0 =< n-1 [
        loop (n-1)..0 'm [
            if a\[m]=a\[n] [
                a\[n+1]: n-m
                break
            ]
        ]
    ]
]

print "The first ten terms of the Van Eck sequence are:"
print first.n:10 a

print ""
print "Terms 991 to 1000 of the sequence are:"
print last.n:10 a


# syntax: GAWK -f VAN_ECK_SEQUENCE.AWK
# converted from Go
BEGIN {
    limit = 1000
    for (i=0; i<limit; i++) {
      arr[i] = 0
    }
    for (n=0; n<limit-1; n++) {
      for (m=n-1; m>=0; m--) {
        if (arr[m] == arr[n]) {
          arr[n+1] = n - m
          break
        }
      }
    }
    printf("terms 1-10:")
    for (i=0; i<10; i++) { printf(" %d",arr[i]) }
    printf("\n")
    printf("terms 991-1000:")
    for (i=990; i<1000; i++) { printf(" %d",arr[i]) }
    printf("\n")
    exit(0)
}


    org $1200
SoundRam equ $1200             ;some assemblers require equ directives to not be indented.
SoundChannel_One equ $1200
SoundChannel_Two equ $1201
SoundChannel_Three equ $1202
     LDA #$FF ;this still gets assembled starting at $1200, since equ directives don't take up space!


*        value of F
         L      2,F                assigment      r2=f
*        reference (or address) of F
         LA     3,F                reference      [email protected]
*        referencing (or indexing) of reg3       (r3->f)
         L      4,0(3)             referencing    r4=%r3=%@f=f


.data
MyVar word 0FFFFh  ;the leading zero is just to help the assembler tell that this is a number, it's not actually part of the variable.

.code

mov ax, word ptr [ds:MyVar]


10 DEFINT A-Z
20 DIM E(1000)
30 FOR I=0 TO 999
40 FOR J=I-1 TO 0 STEP -1
50 IF E(J)=E(I) THEN E(I+1)=I-J: GOTO 80
60 NEXT J
70 E(I+1)=0
80 NEXT I
90 FOR I=0 TO 9: PRINT E(I);: NEXT
95 PRINT
100 FOR I=990 TO 999: PRINT E(I);: NEXT


get "libhdr"

let start() be
$(  let eck = vec 999

    for i = 0 to 999 do eck!i := 0
    for i = 0 to 998 do
        for j = i-1 to 0 by -1 do
            if eck!i = eck!j then
            $(  eck!(i+1) := i-j
                break
            $)

    for i = 0 to 9 do writed(eck!i, 4)
    wrch('*N')
    for i = 990 to 999 do writed(eck!i, 4)
    wrch('*N')
$)


EckStep ← ⊢∾(⊑⊑∘⌽∊1↓⌽)◶(0˙)‿((⊑1+⊑⊐˜ 1↓⊢)⌽)
Eck ← {(EckStep⍟(𝕩-1))⥊0}
(Eck 10)≍990↓Eck 1000


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

int main(int argc, const char *argv[]) {
  const int max = 1000;
  int *a = malloc(max * sizeof(int));
  for (int n = 0; n < max - 1; n ++) {
    for (int m = n - 1; m >= 0; m --) {
      if (a[m] == a[n]) {
        a[n+1] = n - m;
        break;
      }
    }
  }

  printf("The first ten terms of the Van Eck sequence are:\n");
  for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
  printf("\n\nTerms 991 to 1000 of the sequence are:\n");
  for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
  putchar('\n');

  return 0;
}


\ declare a variable which is initialized to the number '0'
var x

\ declare a variable which is initialized to a string "cat"
"cat" var, y

\ Get the value in x, add 20 and store it:
x @ 20 n:+ x !

\ Change the cat to a dog:
"dog" y !


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

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data              */
/*********************************/
.data
szString:         .asciz "String définition"
sArea1:           .fill 11, 1, ' '            // 11 spaces
     // or
sArea2:           .space 11,' '               // 11 spaces

cCharac:          .byte '\n'                  // character
cByte1:           .byte 0b10101               // 1 byte binary value

hHalfWord1:       .hword   0xFF               // 2 bytes value hexa
.align 4
iInteger1:        .int 123456                 // 4 bytes value decimal
iInteger3:        .short 0500                 // 4 bytes value octal
iInteger5:        .int 0x4000                 // 4 bytes value hexa

iInteger7:        .word 0x4000                //   4 bytes value hexa
iInteger6:        .int  04000                 //   4 bytes value octal

TabInteger4:      .int  5,4,3,2               // Area of 4 integers = 4 * 4 = 16 bytes

dDoubleInt1:      .quad  0xFFFFFFFFFFFFFFFF   //  8 bytes value hexa

dfFLOAT1:         .double 0f-31415926535897932384626433832795028841971.693993751E-40 //  Float 8 bytes
sfFLOAT2:         .float  0f-31415926535897932384626433832795028841971.693993751E-40 //  Float 4 bytes (or use .single)

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sBuffer:         .skip  500                      // 500 bytes values zero
iInteger2:       .skip 4                         // 4 bytes value zero
dDoubleint2:     .skip 8                         // 8 bytes value zero
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                            // entry of program
    ldr x0,qAdriInteger2                         // load variable address
    mov x1,#100
    str x1,[x0]                                  // init variable iInteger2

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

qAdriInteger2:             .quad iInteger2       // variable address iInteger2


Name: declare   -- a local declaration block has an optional name
   A : constant Integer := 42;  -- Create a constant
   X : String := "Hello"; -- Create and initialize a local variable
   Y : Integer;           -- Create an uninitialized variable
   Z : Integer renames Y: -- Rename Y (creates a view)
   function F (X: Integer) return Integer is
     -- Inside, all declarations outside are visible when not hidden: X, Y, Z are global with respect to F.
     X: Integer := Z;  -- hides the outer X which however can be referred to by Name.X
   begin
     ...
   end F;  -- locally declared variables stop to exist here
begin
   Y := 1; -- Assign variable
   declare
     X: Float := -42.0E-10;  -- hides the outer X (can be referred to Name.X like in F)
   begin
     ...
   end;
end Name; -- End of the scope


using System.Linq; class Program { static void Main() {
    int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
    for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
        for (d = a, e = b - d, f = h[b]; e <= b; e++)
            if (f == h[d--]) { h[c] = e; break; }
    void sho(int i) { System.Console.WriteLine(string.Join(" ",
        h.Skip(i).Take(10))); } sho(0); sho(990); } }


#include <iostream>
#include <map>

class van_eck_generator {
public:
    int next() {
        int result = last_term;
        auto iter = last_pos.find(last_term);
        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;
        last_pos[last_term] = index;
        last_term = next_term;
        ++index;
        return result;
    }
private:
    int index = 0;
    int last_term = 0;
    std::map<int, int> last_pos;
};

int main() {
    van_eck_generator gen;
    int i = 0;
    std::cout << "First 10 terms of the Van Eck sequence:\n";
    for (; i < 10; ++i)
        std::cout << gen.next() << ' ';
    for (; i < 990; ++i)
        gen.next();
    std::cout << "\nTerms 991 to 1000 of the sequence:\n";
    for (; i < 1000; ++i)
        std::cout << gen.next() << ' ';
    std::cout << '\n';
    return 0;
}


% declare some variables %
integer a1, a2; real b; long real c; complex d; long complex f;
logical g; bits h; string(32) j;

% assign "initial values" %
f := d := c := b := a2 := a1 := 0; % multiple assignment %
g := false; h := #a0; j := "Hello, World!";


// If not initialized at class/member level, it will be set to null
Integer x = 0;
Integer y; // y is null here
Integer p,q,r; // declare multiple variables
Integer i=1,j=2,k=3; // declare and initialize

/*
 * Similar to Integer, below variables can be initialized together separated by ','.
*/
String s = 'a string';
Decimal d = 0.0;
Double dbl = 0.0;
Blob blb = Blob.valueOf('Any String');
Boolean b = true;
AClassName cls = new AClassName();


(defn van-eck
  ([] (van-eck 0 0 {}))
  ([val n seen]
   (lazy-seq
    (cons val
          (let [next (- n (get seen val n))]
            (van-eck next
                     (inc n)
                     (assoc seen val n)))))))

(println "First 10 terms:" (take 10 (van-eck)))
(println "Terms 991 to 1000 terms:" (take 10 (drop 990 (van-eck))))


% Generate the first N elements of the Van Eck sequence
eck = proc (n: int) returns (array[int])
    ai = array[int]
    e: ai := ai$fill(0, n, 0)

    for i: int in int$from_to(ai$low(e), ai$high(e)-1) do
        for j: int in int$from_to_by(i-1, ai$low(e), -1) do
            if e[i] = e[j] then
                e[i+1] := i-j
                break
            end
        end
    end
    return(e)
end eck

% Show 0..9 and 990..999
start_up = proc ()
    po: stream := stream$primary_output()
    e: array[int] := eck(1000)

    stream$puts(po, "  0 -   9: ")
    for i: int in int$from_to(0,9) do
        stream$putright(po, int$unparse(e[i]), 4)
    end
    stream$puts(po, "\n990 - 999: ")
    for i: int in int$from_to(990,999) do
        stream$putright(po, int$unparse(e[i]), 4)
    end
    stream$putl(po, "")
end start_up


        IDENTIFICATION DIVISION.
        PROGRAM-ID. VAN-ECK.

        DATA DIVISION.
        WORKING-STORAGE SECTION.
        01 CALCULATION.
            02 ECK      PIC 999 OCCURS 1000 TIMES.
            02 I        PIC 9999.
            02 J        PIC 9999.
        01 OUTPUT-FORMAT.
            02 ITEM     PIC ZZ9.
            02 IDX      PIC ZZZ9.

        PROCEDURE DIVISION.
        B.  PERFORM GENERATE-ECK.
            PERFORM SHOW VARYING I FROM 1 BY 1 UNTIL I = 11.
            PERFORM SHOW VARYING I FROM 991 BY 1 UNTIL I = 1001.
            STOP RUN.

        SHOW.
            MOVE I TO IDX.
            MOVE ECK(I) TO ITEM.
            DISPLAY 'ECK(' IDX ') = ' ITEM.

        GENERATE-ECK SECTION.
        B.  SET ECK(1) TO 0.
            SET I TO 1.
            PERFORM GENERATE-TERM
                VARYING I FROM 2 BY 1 UNTIL I = 1001.

        GENERATE-TERM SECTION.
        B.  SUBTRACT 2 FROM I GIVING J.
        LOOP.
            IF J IS LESS THAN 1 GO TO TERM-IS-NEW.
            IF ECK(J) = ECK(I - 1) GO TO TERM-IS-OLD.
            SUBTRACT 1 FROM J.
            GO TO LOOP.

        TERM-IS-NEW.
            SET ECK(I) TO 0.
            GO TO DONE.

        TERM-IS-OLD.
            COMPUTE ECK(I) = (I - J) - 1.

        DONE. EXIT.


/* ARM assembly Raspberry PI  */
/*  program variable.s   */

/************************************/
/* Constantes Définition            */
/************************************/
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
/*********************************/
/* Initialized data              */
/*********************************/
.data
szString:         .asciz "String définition"
sArea1:            .fill 11, 1, ' '            @ 11 spaces
     @ or
sArea2:            .space 11,' '               @ 11 spaces

cCharac:          .byte '\n'                   @ character
cByte1:            .byte 0b10101               @ 1 byte binary value

hHalfWord1:       .hword   0xFF                @ 2 bytes value hexa
.align 4
iInteger1:      .int 123456                    @  4 bytes value decimal
iInteger3:      .short 0500                    @  4 bytes value octal
iPointer1:      .int 0x4000                    @   4 bytes value hexa
     @ or
iPointer2:      .word 0x4000                   @   4 bytes value hexa
iPointer3:       .int  04000                   @   4 bytes value octal

TabInteger4:     .int  5,4,3,2                 @ Area of 4 integers = 4 * 4 = 16 bytes

iDoubleInt1:     .quad  0xFFFFFFFFFFFFFFFF     @  8 bytes

dfFLOAT1:       .double 0f-31415926535897932384626433832795028841971.693993751E-40 @  Float 8 bytes
sfFLOAT2:       .float  0f-31415926535897932384626433832795028841971.693993751E-40 @  Float 4 bytes (or use .single)

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sBuffer:         .skip  500                       @ 500 bytes values zero
iInteger2:       .skip 4                          @ 4 bytes value zero
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                             @ entry of program
    ldr r0,iAdriInteger2                          @ load variable address
    mov r1,#100
    str r1,[r0]                                   @ init variable iInteger2

100:                                              @ standard end of the program
    mov r0, #0                                    @ return code
    mov r7, #EXIT                                 @ request to exit program
    svc #0                                        @ perform the system call

iAdriInteger2:             .int iInteger2         @ variable address iInteger2


;;Tested using CLISP

(defun VanEck (x) (reverse (VanEckh x 0 0 '(0))))

(defun VanEckh (final index curr lst)
	(if (eq index final)
		lst
		(VanEckh final (+ index 1) (howfar curr lst) (cons curr lst))))

(defun howfar (x lst) (howfarh x lst 0))

(defun howfarh (x lst runningtotal)
	(cond
		((null lst) 0)
		((eq x (car lst)) (+ runningtotal 1))
		(t (howfarh x (cdr lst) (+ runningtotal 1)))))

(format t "The first 10 elements are ~a~%" (VanEck 9))
(format t "The 990-1000th elements are ~a~%" (nthcdr 990 (VanEck 999)))


include "cowgol.coh";

sub print_list(ptr: [uint16], n: uint8) is
    while n > 0 loop
        print_i16([ptr]);
        print_char(' ');
        n := n - 1;
        ptr := @next ptr;
    end loop;
    print_nl();
end sub;

const LIMIT := 1000;
var eck: uint16[LIMIT];
MemZero(&eck as [uint8], @bytesof eck);
var i: @indexof eck;
var j: @indexof eck;

i := 0;
while i < LIMIT-1 loop
    j := i-1;
    while j != -1 loop
        if eck[i] == eck[j] then
            eck[i+1] := i-j;
            break;
        end if;
        j := j - 1;
    end loop;
    i := i + 1;
end loop;

print_list(&eck[0], 10);
print_list(&eck[LIMIT-10], 10);


num: 10
str: "hello world"

arrA: [1 2 3]
arrB: ["one" "two" "three"]
arrC: [1 "two" [3 4 5]]
arrD: ["one" true [ print "something" ]]

dict: [
	name: "john"
	surname: "doe"
	function: $[][
		print "do sth"
	]
]

inspect symbols


x = hello       ; assign verbatim as a string
z := 3 + 4      ; assign an expression
if !y       ; uninitialized variables are assumed to be 0 or "" (blank string)
Msgbox %x%  ; variable dereferencing is done by surrounding '%' signs
fx()
{
local x   ; variable default scope in a function is local anyways
global y  ;
static z=4  ; initialized once, then value is remembered between function calls
}


BEGIN {
# Variables are dynamically typecast, and do not need declaration prior to use:
  fruit = "banana"    # create a variable, and fill it with a string
  a = 1               # create a variable, and fill it with a numeric value
  a = "apple"         # re-use the above variable for a string
  print a, fruit

# Multiple assignments are possible from within a single statement:
  x = y = z = 3
  print "x,y,z:", x,y,z

# "dynamically typecast" means the content of a variable is used
# as needed by the current operation, e.g. for a calculation:
  a = "1"
  b = "2banana"
  c = "3*4"

  print "a,b,c=",a,b,c,  "c+0=", c+0, 0+c
  print "a+b=", a+b, "b+c=", b+c
}


import std.stdio;

void vanEck(int firstIndex, int lastIndex) {
    int[int] vanEckMap;
    int last = 0;
    if (firstIndex == 1) {
        writefln("VanEck[%d] = %d", 1, 0);
    }
    for (int n = 2; n <= lastIndex; n++) {
        int vanEck = last in vanEckMap ? n - vanEckMap[last] : 0;
        vanEckMap[last] = n;
        last = vanEck;
        if (n >= firstIndex) {
            writefln("VanEck[%d] = %d", n, vanEck);
        }
    }
}

void main() {
    writeln("First 10 terms of Van Eck's sequence:");
    vanEck(1, 10);
    writeln;
    writeln("Terms 991 to 1000 of Van Eck's sequence:");
    vanEck(991, 1000);
}


/* Fill array with Van Eck sequence */
proc nonrec make_eck([*] word eck) void:
    int i, j, max;
    max := dim(eck,1)-1;
    for i from 0 upto max do eck[i] := 0 od;

    for i from 0 upto max-1 do
        j := i - 1;
        while j >= 0 and eck[i] ~= eck[j] do
            j := j - 1
        od;
        if j >= 0 then
            eck[i+1] := i - j
        fi
    od
corp

/* Print eck[0..9] and eck[990..999] */
proc nonrec main() void:
    word i;
    [1000] word eck;
    make_eck(eck);

    for i from 0 upto 9 do write(eck[i]:4) od;
    writeln();
    for i from 990 upto 999 do write(eck[i]:4) od;
    writeln()
corp


10 LET A=1.3
20 LET B%=1.3:       REM The sigil indicates an integer, so this will be rounded down
30 LET C$="0121":    REM The sigil indicates a string data type. the leading zero is not truncated
40 DIM D(10):        REM Create an array of 10 digits
50 DIM E$(5.10):     REM Create an array of 5 strings, with a maximum length of 10 characters
60 LET D(1)=1.3:     REM Assign the first element of d
70 LET E$(3)="ROSE": REM Assign a value to the third string
80 PRINT D(3):       REM Unassigned array elements have a default value of zero
90 PRINT E$(3):      REM Ten spaces because string arrays are not dynamic
100 PRINT E$(3);"TTA CODE": REM There will be spaces between rose and etta
110 DIM F%(10):  REM Integers use less space than floating point values
120 PRINT G:     REM This is an error because f has not been defined
130 PRINT D(0):  REM This is an error because elements are numbered from one
140 LET D(11)=6: REM This is an error because d only has 10 elements
150 PRINT F%:    REM This is an error because we have not provided an element number
160 END


@echo off

::setting variables in defferent ways
set myInt1=5
set myString1=Rosetta Code
set "myInt2=5"
set "myString2=Rosetta Code"

::Arithmetic
set /a myInt1=%myInt1%+1
set /a myInt2+=1
set /a myInt3=myInt2+   5

set myInt
set myString
pause>nul


F scalartriplep(a, b, c)
    return dot(a, cross(b, c))

F vectortriplep(a, b, c)
    return cross(a, cross(b, c))

V a = (3, 4, 5)
V b = (4, 3, 5)
V c = (-5, -12, -13)

print(‘a = #.;  b = #.;  c = #.’.format(a, b, c))
print(‘a . b = #.’.format(dot(a, b)))
print(‘a x b = #.’.format(cross(a,b)))
print(‘a . (b x c) = #.’.format(scalartriplep(a, b, c)))
print(‘a x (b x c) = #.’.format(vectortriplep(a, b, c)))


let max = 1000
var a = Array.Empty(max, 0)
for n in 0..(max-2) {
    var m = n - 1
    while m >= 0 {
        if a[m] == a[n] {
            a[n+1] = n - m
            break
        }
        m -= 1
    }
}
print("The first ten terms of the Van Eck sequence are: \(a[0..10].ToArray())")
print("Terms 991 to 1000 of the sequence are: \(a[991..999].ToArray())")


// Generate Van Eck's Sequence. Nigel Galloway: June 19th., 2019
let ecK()=let n=System.Collections.Generic.Dictionary<int,int>()
          Seq.unfold(fun (g,e)->Some(g,((if n.ContainsKey g then let i=n.[g] in n.[g]<-e;e-i else n.[g]<-e;0),e+1)))(0,0)


USING: assocs fry kernel make math namespaces prettyprint
sequences ;

: van-eck ( n -- seq )
    [
        0 , 1 - H{ } clone '[
            building get [ length 1 - ] [ last ] bi _ 3dup
            2dup key? [ at - ] [ 3drop 0 ] if , set-at
        ] times
    ] { } make ;

1000 van-eck 10 [ head ] [ tail* ] 2bi [ . ] [email protected]


      program VanEck
      implicit none
      integer eck(1000), i, j

      eck(1) = 0
      do 20 i=1, 999
          do 10 j=i-1, 1, -1
              if (eck(i) .eq. eck(j)) then
                  eck(i+1) = i-j
                  go to 20
              end if
 10       continue
          eck(i+1) = 0
 20   continue

      do 30 i=1, 10
 30       write (*,'(I4)',advance='no') eck(i)
      write (*,*)

      do 40 i=991, 1000
 40       write (*,'(I4)',advance='no') eck(i)
      write (*,*)

      end program


      REM BBC BASIC (for Windows) has the following scalar variable types;
      REM the type is explicitly indicated by means of a suffix character.
      REM Variable names must start with A-Z, a-z, _ or `, and may contain
      REM any of those characters plus 0-9 and @; they are case-sensitive.

      A& = 123      : REM Unsigned 8-bit byte (0 to 255)
      A% = 12345678 : REM Signed 32-bit integer (-2147483648 to +2147483647)
      A  = 123.45E6 : REM Variant 40-bit float or 32-bit integer (no suffix)
      A# = 123.45E6 : REM Variant 64-bit double or 32-bit integer
      A$ = "Abcdef" : REM String (0 to 65535 bytes)

      REM Scalar variables do not need to be declared but must be initialised
      REM before being read, otherwise a 'No such variable' error is reported
      REM The static integer variables A% to Z% are permanently defined.

      REM BBC BASIC also has indirection operators which allow variable-like
      REM entities to be created in memory:

      DIM addr 7    : REM Allocate 8 bytes of heap
      ?addr = 123   : REM Unsigned 8-bit byte (0 to 255)
      !addr = 12345 : REM Signed 32-bit integer (-2147483648 to +2147483647)
      |addr = 12.34 : REM Variant 40-bit or 64-bit float or 32-bit integer
      $addr = "Abc" : REM String terminated by CR (0 to 65535 bytes)
      $$addr = "Abc": REM String terminated by NUL (0 to 65535 bytes)

      REM The integer indirection operators may be used in a dyadic form:
      offset = 4
      addr?offset = 12345678 : REM Unsigned 8-bit byte at addr+offset
      addr!offset = 12345678 : REM Signed 32-bit integer at addr+offset

      REM All variables in BBC BASIC have global scope unless they are used
      REM as a formal parameter of a function or procedure, or are declared
      REM as LOCAL or PRIVATE.  This is different from most other BASICs.


TYPE Vector=[INT x,y,z]

PROC CreateVector(INT vx,vy,vz Vector POINTER v)
  v.x=vx v.y=vy v.z=vz
RETURN

PROC PrintVector(Vector POINTER v)
  PrintF("(%I,%I,%I)",v.x,v.y,v.z)
RETURN

INT FUNC DotProduct(Vector POINTER v1,v2)
  INT res

  res=v1.x*v2.x    ;calculation split into parts
  res==+v1.y*v2.y  ;otherwise incorrect result
  res==+v1.z*v2.z  ;is returned
RETURN (res)

PROC CrossProduct(Vector POINTER v1,v2,res)
  res.x=v1.y*v2.z    ;calculation split into parts
  res.x==-v1.z*v2.y  ;otherwise incorrect result
  res.y=v1.z*v2.x    ;is returned
  res.y==-v1.x*v2.z
  res.z=v1.x*v2.y
  res.z==-v1.y*v2.x
RETURN

PROC Main()
  Vector a,b,c,d,e
  INT res

  CreateVector(3,4,5,a)
  CreateVector(4,3,5,b)
  CreateVector(-5,-12,-13,c)

  Print("a=") PrintVector(a) PutE()
  Print("b=") PrintVector(b) PutE()
  Print("c=") PrintVector(c) PutE()
  PutE()

  res=DotProduct(a,b)
  PrintF("a.b=%I%E",res)

  CrossProduct(a,b,d)
  Print("axb=") PrintVector(d) PutE()

  CrossProduct(b,c,d)
  res=DotProduct(a,d)
  PrintF("a.(bxc)=%I%E",res)

  CrossProduct(b,c,d)
  CrossProduct(a,d,e)
  Print("ax(bxc)=") PrintVector(e) PutE()
RETURN


with Ada.Text_IO;

procedure Vector is
   type Float_Vector is array (Positive range <>) of Float;
   package Float_IO is new Ada.Text_IO.Float_IO (Float);

   procedure Vector_Put (X : Float_Vector) is
   begin
      Ada.Text_IO.Put ("(");
      for I in X'Range loop
         Float_IO.Put (X (I), Aft => 1, Exp => 0);
         if I /= X'Last then
            Ada.Text_IO.Put (", ");
         end if;
      end loop;
      Ada.Text_IO.Put (")");
   end Vector_Put;

   -- cross product
   function "*" (Left, Right : Float_Vector) return Float_Vector is
   begin
      if Left'Length /= Right'Length then
         raise Constraint_Error with "vectors of different size in dot product";
      end if;
      if Left'Length /= 3 then
         raise Constraint_Error with "dot product only implemented for R**3";
      end if;
      return Float_Vector'(Left (Left'First + 1) * Right (Right'First + 2) -
                             Left (Left'First + 2) * Right (Right'First + 1),
                           Left (Left'First + 2) * Right (Right'First) -
                             Left (Left'First) * Right (Right'First + 2),
                           Left (Left'First) * Right (Right'First + 1) -
                             Left (Left'First + 1) * Right (Right'First));
   end "*";

   -- scalar product
   function "*" (Left, Right : Float_Vector) return Float is
      Result : Float := 0.0;
      I, J : Positive;
   begin
      if Left'Length /= Right'Length then
         raise Constraint_Error with "vectors of different size in scalar product";
      end if;
      I := Left'First; J := Right'First;
      while I <= Left'Last and then J <= Right'Last loop
         Result := Result + Left (I) * Right (J);
         I := I + 1; J := J + 1;
      end loop;
      return Result;
   end "*";

   -- stretching
   function "*" (Left : Float_Vector; Right : Float) return Float_Vector is
      Result : Float_Vector (Left'Range);
   begin
      for I in Left'Range loop
         Result (I) := Left (I) * Right;
      end loop;
      return Result;
   end "*";

   A : constant Float_Vector := (3.0, 4.0, 5.0);
   B : constant Float_Vector := (4.0, 3.0, 5.0);
   C : constant Float_Vector := (-5.0, -12.0, -13.0);
begin
   Ada.Text_IO.Put ("A: "); Vector_Put (A); Ada.Text_IO.New_Line;
   Ada.Text_IO.Put ("B: "); Vector_Put (B); Ada.Text_IO.New_Line;
   Ada.Text_IO.Put ("C: "); Vector_Put (C); Ada.Text_IO.New_Line;
   Ada.Text_IO.New_Line;
   Ada.Text_IO.Put ("A dot B = "); Float_IO.Put (A * B, Aft => 1, Exp => 0);
   Ada.Text_IO.New_Line;
   Ada.Text_IO.Put ("A x B = "); Vector_Put (A * B);
   Ada.Text_IO.New_Line;
   Ada.Text_IO.Put ("A dot (B x C) = "); Float_IO.Put (A * (B * C), Aft => 1, Exp => 0);
   Ada.Text_IO.New_Line;
   Ada.Text_IO.Put ("A x (B x C) = "); Vector_Put (A * Float_Vector'(B * C));
   Ada.Text_IO.New_Line;
end Vector;


Const limite = 1000

Dim As Integer a(limite), n, m, i

For n = 0 To limite-1
    For m = n-1 To 0 Step -1
        If a(m) = a(n) Then a(n+1) = n-m: Exit For
    Next m
Next n

Print "Secuencia de Van Eck:" &Chr(10)
Print "Primeros 10 terminos: ";
For i = 0 To 9
    Print a(i) &" ";
Next i
Print Chr(10) & "Terminos 991 al 1000: ";
For i = 990 To 999
    Print a(i) &" ";
Next i
End


package main

import "fmt"

func main() {
    const max = 1000
    a := make([]int, max) // all zero by default
    for n := 0; n < max-1; n++ {
        for m := n - 1;  m >= 0; m-- {
            if a[m] == a[n] {
                a[n+1] = n - m
                break
            }
        }
    }
    fmt.Println("The first ten terms of the Van Eck sequence are:")
    fmt.Println(a[:10])
    fmt.Println("\nTerms 991 to 1000 of the sequence are:")
    fmt.Println(a[990:])
}


MODE FIELD = INT;
FORMAT field fmt = $g(-0)$;

MODE VEC = [3]FIELD;
FORMAT vec fmt = $"("f(field fmt)", "f(field fmt)", "f(field fmt)")"$;

PROC crossp = (VEC a, b)VEC:(
    #Cross product of two 3D vectors#
    CO ASSERT(LWB a = LWB b AND UPB a = UPB b AND UPB b = 3 # "For 3D vectors only" #); CO
    (a[2]*b[3] - a[3]*b[2], a[3]*b[1] - a[1]*b[3], a[1]*b[2] - a[2]*b[1])
);

PRIO MAXLWB = 8, MINUPB=8;

OP MAXLWB = (VEC a, b)INT: (LWB a<LWB b|LWB a|LWB b);
OP MINUPB = (VEC a, b)INT: (UPB a>UPB b|UPB a|UPB b);

PROC dotp = (VEC a, b)FIELD:(
    #Dot product of two vectors#
    FIELD sum := 0;
    FOR i FROM a MAXLWB b TO a MINUPB b DO sum +:= a[i]*b[i] OD;
    sum
);

PROC scalartriplep = (VEC a, b, c)VEC:(
    #Scalar triple product of three vectors: "a . (b x c)"#
    dotp(a, crossp(b, c))
);

PROC vectortriplep = (VEC a, b, c)VEC:(
    #Vector triple product of three vectors: "a x (b x c)"#
    crossp(a, crossp(b, c))
);

# Declare some useful operators #
PRIO DOT = 5, X = 5;
OP (VEC, VEC)FIELD DOT = dotp;
OP (VEC, VEC)VEC X = crossp;

main:(
    VEC a=(3, 4, 5), b=(4, 3, 5), c=(-5, -12, -13);
    printf(($"a = "f(vec fmt)";  b = "f(vec fmt)";  c = "f(vec fmt)l$ , a, b, c));
    printf($"Using PROCedures:"l$);
    printf(($"a . b = "f(field fmt)l$, dotp(a,b)));
    printf(($"a x b = "f(vec fmt)l$, crossp(a,b)));
    printf(($"a . (b x c) = "f(field fmt)l$, scalartriplep(a, b, c)));
    printf(($"a x (b x c) = "f(vec fmt)l$, vectortriplep(a, b, c)));
    printf($"Using OPerators:"l$);
    printf(($"a . b = "f(field fmt)l$, a DOT b));
    printf(($"a x b = "f(vec fmt)l$, a X b));
    printf(($"a . (b x c) = "f(field fmt)l$, a DOT (b X c)));
    printf(($"a x (b x c) = "f(vec fmt)l$, a X (b X c)))
)


import Data.List (elemIndex)
import Data.Maybe (maybe)

vanEck :: Int -> [Int]
vanEck n = reverse $ iterate go [] !! n
  where
    go [] = [0]
    go xxs@(x:xs) = maybe 0 succ (elemIndex x xs) : xxs

main :: IO ()
main = do
  print $ vanEck 10
  print $ drop 990 (vanEck 1000)


set MyStr = "A string"
set MyInt = 4
set MyFloat = 1.3


begin
    % define the Vector record type                                          %
    record Vector( integer X, Y, Z );

    % calculates the dot product of two Vectors                              %
    integer procedure dotProduct( reference(Vector) value A, B ) ;
        ( X(A) * X(B) ) + ( Y(A) * Y(B) ) + ( Z(A) * Z(B) );

    % calculates the cross product or two Vectors                            %
    reference(Vector) procedure crossProduct( reference(Vector) value A, B ) ;
        Vector( ( Y(A) * Z(B) ) - ( Z(A) * Y(B) )
              , ( Z(A) * X(B) ) - ( X(A) * Z(B) )
              , ( X(A) * Y(B) ) - ( Y(A) * X(B) )
              );

    % calculates the scaler triple product of two vectors                    %
    integer procedure scalerTripleProduct( reference(Vector) value A, B, C ) ;
        dotProduct( A, crossProduct( B, C ) );

    % calculates the vector triple product of two vectors                    %
    reference(Vector) procedure vectorTripleProduct( reference(Vector) value A, B, C ) ;
        crossProduct( A, crossProduct( B, C ) );

    % test the Vector routines                                               %
    begin
        procedure writeonVector( reference(Vector) value v ) ;
            writeon( "(", X(v), ", ", Y(v), ", ", Z(v), ")" );

        Reference(Vector) a, b, c;

        a := Vector(  3,   4,   5 );
        b := Vector(  4,   3,   5 );
        c := Vector( -5, -12, -13 );

        i_w := 1; s_w := 0; % set output formatting                          %

        write( "            a: " ); writeonVector( a );
        write( "            b: " ); writeonVector( b );
        write( "            c: " ); writeonVector( c );
        write( "        a . b: ", dotProduct( a, b ) );
        write( "        a x b: " ); writeonVector( crossProduct( a, b ) );
        write( "a . ( b x c ): ", scalerTripleProduct( a, b, c ) );
        write( "a x ( b x c ): " ); writeonVector( vectorTripleProduct( a, b, c ) )
    end
end.


import java.util.HashMap;
import java.util.Map;

public class VanEckSequence {

    public static void main(String[] args) {
        System.out.println("First 10 terms of Van Eck's sequence:");
        vanEck(1, 10);
        System.out.println("");
        System.out.println("Terms 991 to 1000 of Van Eck's sequence:");
        vanEck(991, 1000);
    }

    private static void vanEck(int firstIndex, int lastIndex) {
        Map<Integer,Integer> vanEckMap = new HashMap<>();
        int last = 0;
        if ( firstIndex == 1 ) {
            System.out.printf("VanEck[%d] = %d%n", 1, 0);
        }
        for ( int n = 2 ; n <= lastIndex ; n++ ) {
            int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;
            vanEckMap.put(last, n);
            last = vanEck;
            if ( n >= firstIndex ) {
                System.out.printf("VanEck[%d] = %d%n", n, vanEck);
            }
        }

    }

}


MOVE 5 TO x
MOVE FUNCTION SOME-FUNC(x) TO y
MOVE "foo" TO z
MOVE "values 1234" TO group-item
SET some-index TO 5


--------------------- VECTOR PRODUCTS ---------------------

-- dotProduct :: Num a => [a] -> [a] -> Either String a
on dotProduct(xs, ys)
    -- Dot product of two vectors of equal dimension.

    if length of xs = length of ys then
        |Right|(sum(zipWith(my mul, xs, ys)))
    else
        |Left|("Dot product not defined for vectors of differing dimension.")
    end if
end dotProduct

-- crossProduct :: Num a => (a, a, a) -> (a, a, a)
-- Either String -> (a, a, a)
on crossProduct(xs, ys)
    -- The cross product of two 3D vectors.

    if 3 ≠ length of xs or 3 ≠ length of ys then
        |Left|("Cross product is defined only for 3d vectors.")
    else
        set {x1, x2, x3} to xs
        set {y1, y2, y3} to ys
        |Right|({¬
            x2 * y3 - x3 * y2, ¬
            x3 * y1 - x1 * y3, ¬
            x1 * y2 - x2 * y1})
    end if
end crossProduct

-- scalarTriple :: Num a => (a, a, a) -> (a, a, a) -> (a, a a) ->
-- Either String -> a
on scalarTriple(q, r, s)
    -- The scalar triple product.

    script go
        on |λ|(ys)
            dotProduct(q, ys)
        end |λ|
    end script
    bindLR(crossProduct(r, s), go)
end scalarTriple

-- vectorTriple :: Num a => (a, a, a) -> (a, a, a) -> (a, a a) ->
-- Either String -> (a, a, a)
on vectorTriple(q, r, s)
    -- The vector triple product.

    script go
        on |λ|(ys)
            crossProduct(q, ys)
        end |λ|
    end script
    bindLR(crossProduct(r, s), go)
end vectorTriple

-------------------------- TEST ---------------------------
on run
    set a to {3, 4, 5}
    set b to {4, 3, 5}
    set c to {-5, -12, -13}
    set d to {3, 4, 5, 6}

    script test
        on |λ|(f)
            either(my identity, my show, ¬
                mReturn(f)'s |λ|(a, b, c, d))
        end |λ|
    end script

    tell test
        unlines({¬
            "a . b = " & |λ|(dotProduct), ¬
            "a x b = " & |λ|(crossProduct), ¬
            "a . (b x c) = " & |λ|(scalarTriple), ¬
            "a x (b x c) = " & |λ|(vectorTriple), ¬
            "a x d = " & either(my identity, my show, ¬
            dotProduct(a, d)), ¬
            "a . (b x d) = " & either(my identity, my show, ¬
            scalarTriple(a, b, d)) ¬
            })
    end tell
end run

-------------------- GENERIC FUNCTIONS --------------------

-- Left :: a -> Either a b
on |Left|(x)
    {type:"Either", |Left|:x, |Right|:missing value}
end |Left|

-- Right :: b -> Either a b
on |Right|(x)
    {type:"Either", |Left|:missing value, |Right|:x}
end |Right|

-- bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
on bindLR(m, mf)
    if missing value is not |Left| of m then
        m
    else
        mReturn(mf)'s |λ|(|Right| of m)
    end if
end bindLR

-- either :: (a -> c) -> (b -> c) -> Either a b -> c
on either(lf, rf, e)
    if missing value is |Left| of e then
        tell mReturn(rf) to |λ|(|Right| of e)
    else
        tell mReturn(lf) to |λ|(|Left| of e)
    end if
end either

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

-- identity :: a -> a
on identity(x)
    -- The argument unchanged.
    x
end identity

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

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

-- min :: Ord a => a -> a -> a
on min(x, y)
    if y < x then
        y
    else
        x
    end if
end min

-- mul :: Num a :: a -> a -> a
on mul(x, y)
    x * y
end mul

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

-- show :: a -> String
on show(x)
    if list is class of x then
        showList(x)
    else
        str(x)
    end if
end show

-- showList :: [a] -> String
on showList(xs)
    "[" & intercalate(", ", map(my str, xs)) & "]"
end showList

-- str :: a -> String
on str(x)
    x as string
end str

-- sum :: [Number] -> Number
on sum(xs)
    script add
        on |λ|(a, b)
            a + b
        end |λ|
    end script

    foldl(add, 0, xs)
end sum

-- unlines :: [String] -> String
on unlines(xs)
    -- A single string formed by the intercalation
    -- of a list of strings with the newline character.
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, linefeed}
    set s to xs as text
    set my text item delimiters to dlm
    s
end unlines

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


(() => {
    'use strict';

    // vanEck :: Int -> [Int]
    const vanEck = n =>
        reverse(
            churchNumeral(n)(
                xs => 0 < xs.length ? cons(
                    maybe(
                        0, succ,
                        elemIndex(xs[0], xs.slice(1))
                    ),
                    xs
                ) : [0]
            )([])
        );

    // TEST -----------------------------------------------
    const main = () => {
        console.log('VanEck series:\n')
        showLog('First 10 terms', vanEck(10))
        showLog('Terms 991-1000', vanEck(1000).slice(990))
    };

    // GENERIC FUNCTIONS ----------------------------------

    // Just :: a -> Maybe a
    const Just = x => ({
        type: 'Maybe',
        Nothing: false,
        Just: x
    });

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: 'Maybe',
        Nothing: true,
    });

    // churchNumeral :: Int -> (a -> a) -> a -> a
    const churchNumeral = n => f => x =>
        Array.from({
            length: n
        }, () => f)
        .reduce((a, g) => g(a), x)

    // cons :: a -> [a] -> [a]
    const cons = (x, xs) => [x].concat(xs)

    // elemIndex :: Eq a => a -> [a] -> Maybe Int
    const elemIndex = (x, xs) => {
        const i = xs.indexOf(x);
        return -1 === i ? (
            Nothing()
        ) : Just(i);
    };

    // maybe :: b -> (a -> b) -> Maybe a -> b
    const maybe = (v, f, m) =>
        m.Nothing ? v : f(m.Just);

    // reverse :: [a] -> [a]
    const reverse = xs =>
        'string' !== typeof xs ? (
            xs.slice(0).reverse()
        ) : xs.split('').reverse().join('');

    // showLog :: a -> IO ()
    const showLog = (...args) =>
        console.log(
            args
            .map(JSON.stringify)
            .join(' -> ')
        );

    // succ :: Int -> Int
    const succ = x => 1 + x;

    // MAIN ---
    return main();
})();


float bite = 36.321;	///_Defines a floating-point number (float), "bite", with a value of 36.321
float[3] bites;		///_Defines a static array of 3 floats
float[] more_bites;	///_Defines a dynamic array of floats


;
;       Variables examples for DBL version 4 by Dario B.
;

.DEFINE NR,10           ;const
.DEFINE AP,"PIPPO"      ;const

        RECORD CUSTOM
COD,    D5
NAME,   A80
ZIP,    D6
CITY,   A80
;-----------------------

        RECORD

ALPHA,  A5             ;alphanumeric
NUMBR,  D5             ;number
DECML,  F5.2           ;float
NUMVE,  10D5           ;array of number
NUMAR,  [10,2]D5       ;array of number
ALPV1,  10A8           ;array of alphanumeric
ALPV2,  [NR]A8         ;array of alphanumeric
ALPA1,  [10,2]A8       ;array of alphanumeric

NUMV,   3D3,100,200,300
ALPV,   2A3,'ABC','FGH','KLM'
MSX,    A9,"VARIABLES"
MSG,    A*,'Esempio di variabile autodimensionante'

        PROC
;-----------------------------------------------------------------------

     CLEAR ALPHA,NUMBR,DEML,NUMVE(1:10*5),NUMAR(1:10*2*5),ALPV1(1:10*8)
     CLEAR ALPV2(1:10*8),ALPA1(1:10*2*8)

     ALPHA="PIPPO"
     NUMBR=10
     DECML=20.55

     CLEAR CUSTOM
     COD=1050
     NAME='Dario Benenati'
     ZIP=27100
     CITY="PAVIA"

     NUMVE(1:10*5)=
     NUMVE(1)=1
     SET NUMVE(2),NUMVE(3),NUMVE(4)=2

     NUMAR(1:10*2*5)=
     NUMAR[1,1]=11
     NUMAR[1,2]=12
     NUMAR[2,1]=21
     NUMAR[2,2]=22

     ALPV1(1:10*8)=
     ALPV1(1)="PIPPO"
     APLV1(2)="PLUTO"
     APLV1(2)="ABCDEFGHIJKLMNOP"       ;ALPV(3)='IJKLMNOP'

     ALPV2(1:10*8)="                   "
     ALPV2[1]="PIPPO"
     ALPV2(2)="PLUTO"
     ALPV2[3](3:2)="FO"
     ALPV2[4](3,4)="FO"

     SET ALPA1[1,1],ALPA1[1,2]="PLUTO"
     ALPA1[2,1](3:2)="FO"
     ALPA1[2,1](3,4)="FO"
     ;.....................


var
  i: Integer;
  s: string;
  o: TObject;
begin
  i := 123;
  s := 'abc';
  o := TObject.Create;
  try
    // ...
  finally
    o.Free;
  end;
end;


; dot product
dot: function [a b][
    sum map couple a b => product
]

; cross product
cross: function [a b][
    A: (a\1 * b\2) - a\2 * b\1
    B: (a\2 * b\0) - a\0 * b\2
    C: (a\0 * b\1) - a\1 * b\0
    @[A B C]
]

; scalar triple product
stp: function [a b c][
    dot a cross b c
]

; vector triple product
vtp: function [a b c][
    cross a cross b c
]

; task
a: [3 4 5]
b: [4 3 5]
c: @[neg 5 neg 12 neg 13]

print ["a • b =", dot a b]
print ["a x b =", cross a b]
print ["a • (b x c) =", stp a b c]
print ["a x (b x c) =", vtp a b c]


V := {a: [3, 4, 5], b: [4, 3, 5], c: [-5, -12, -13]}

for key, val in V
	Out .= key " = (" val[1] ", " val[2] ", " val[3] ")`n"

CP := CrossProduct(V.a, V.b)
VTP := VectorTripleProduct(V.a, V.b, V.c)

MsgBox, % Out "`na • b = " DotProduct(V.a, V.b) "`n"
	. "a x b = (" CP[1] ", " CP[2] ", " CP[3] ")`n"
	. "a • b x c = " ScalerTripleProduct(V.a, V.b, V.c) "`n"
	. "a x b x c = (" VTP[1] ", " VTP[2] ", " VTP[3] ")"

DotProduct(v1, v2) {
	return, v1[1] * v2[1] + v1[2] * v2[2] + v1[3] * v2[3]
}

CrossProduct(v1, v2) {
	return, [v1[2] * v2[3] - v1[3] * v2[2]
	      ,  v1[3] * v2[1] - v1[1] * v2[3]
	      ,  v1[1] * v2[2] - v1[2] * v2[1]]
}

ScalerTripleProduct(v1, v2, v3) {
	return, DotProduct(v1, CrossProduct(v2, v3))
}

VectorTripleProduct(v1, v2, v3) {
	return, CrossProduct(v1, CrossProduct(v2, v3))
}


# Input: an array
# If the rightmost element, .[-1], does not occur elsewhere, return 0;
# otherwise return the "depth" of its rightmost occurrence in .[0:-2]
def depth:
  .[-1] as $x
  | length as $length
  | first(range($length-2; -1; -1) as $i
          | select(.[$i] == $x) | $length - 1 - $i)
     // 0 ;

# Generate a stream of the first $n van Eck integers:
def vanEck($n):
  def v:
    recurse( if length == $n then empty
             else . + [depth] end );
  [0] | v | .[-1];

# The task:
[vanEck(10)], [vanEck(1000)][990:1001]


function vanecksequence(N, startval=0)
    ret = zeros(Int, N)
    ret[1] = startval
    for i in 1:N-1
        lastseen = findlast(x -> x == ret[i], ret[1:i-1])
        if lastseen != nothing
            ret[i + 1] = i - lastseen
        end
    end
    ret
end

println(vanecksequence(10))
println(vanecksequence(1000)[991:1000])