Module Module1

    Function ToVlq(v As ULong) As ULong
        Dim array(8) As Byte
        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray
        buffer.CopyTo(array, 0)
        Return BitConverter.ToUInt64(array, 0)
    End Function

    Function FromVlq(v As ULong) As ULong
        Dim collection = BitConverter.GetBytes(v).Reverse()
        Return FromVlqCollection(collection)
    End Function

    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)
        If v > Math.Pow(2, 56) Then
            Throw New OverflowException("Integer exceeds max value.")
        End If

        Dim index = 7
        Dim significantBitReached = False
        Dim mask = &H7FUL << (index * 7)
        While index >= 0
            Dim buffer = mask And v
            If buffer > 0 OrElse significantBitReached Then
                significantBitReached = True
                buffer >>= index * 7
                If index > 0 Then
                    buffer = buffer Or &H80
                End If
                Yield buffer
            End If
            mask >>= 7
            index -= 1
        End While
    End Function

    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong
        Dim v = 0UL
        Dim significantBitReached = False

        Using enumerator = vlq.GetEnumerator
            Dim index = 0
            While enumerator.MoveNext
                Dim buffer = enumerator.Current
                If buffer > 0 OrElse significantBitReached Then
                    significantBitReached = True
                    v <<= 7
                    v = v Or (buffer And &H7FUL)
                End If

                index += 1
                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then
                    Exit While
                End If
            End While
        End Using

        Return v
    End Function

    Sub Main()
        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}
        For Each original In values
            Console.WriteLine("Original: 0x{0:X}", original)

            REM collection
            Dim seq = ToVlqCollection(original)
            Console.WriteLine("Sequence: 0x{0}", seq.Select(Function(b) b.ToString("X2")).Aggregate(Function(a, b) String.Concat(a, b)))

            Dim decoded = FromVlqCollection(seq)
            Console.WriteLine("Decoded: 0x{0:X}", decoded)

            REM ints
            Dim encoded = ToVlq(original)
            Console.WriteLine("Encoded: 0x{0:X}", encoded)

            decoded = FromVlq(encoded)
            Console.WriteLine("Decoded: 0x{0:X}", decoded)

            Console.WriteLine()
        Next
    End Sub

End Module


import "/fmt" for Fmt, Conv
import "/str" for Str

var toOctets = Fn.new { |n|
    var s = Conv.itoa(n, 2)
    var le = s.count
    var r = le % 7
    var d = (le/7).floor
    if (r > 0) {
        d = d + 1
        s = Fmt.zfill(7 * d, s)
    }
    var chunks = Str.chunks(s, 7)
    var last = "0" + chunks[-1]
    s = chunks[0..-2].map { |ch| "1" + ch }.join() + last
    return Str.chunks(s, 8).map { |ch| Conv.atoi(ch, 2) }.toList
}

var fromOctets = Fn.new { |octets|
    var s = ""
    for (oct in octets) {
        var bin = Conv.itoa(oct, 2)
        bin = Fmt.zfill(7, bin)
        s = s + bin[-7..-1]
    }
    return Conv.atoi(s, 2)
}

var tests = [2097152, 2097151]
for (test in tests) {
    var octets = toOctets.call(test)
    var display = octets.map { |oct| "Ox" + Fmt.xz(2, oct) }.toList
    System.write("%(test) -> %(Fmt.v("s", 4, display, 0, " ", "")) -> ")
    System.print(fromOctets.call(octets))
}


(defun print-all-fn (xs)
   (if (endp xs)
       nil
       (prog2$ (cw "~x0~%" (first xs))
               (print-all-fn (rest xs)))))

(defmacro print-all (&rest args)
   `(print-all-fn (quote ,args)))


func OctIn(Dev);                \Input from device value of sequence of octets
int  Dev, N, Oct;
[N:= 0;
repeat  Oct:= HexIn(Dev);
        N:= N<<7 + (Oct&$7F);
until   (Oct&$80) = 0;
return N;
];

proc OctOut(Dev, Num, Lev);     \Output value to device as sequence of octets
int  Dev, Num, Lev, Rem;
[Rem:= Num & $7F;
Num:= Num >> 7;
if Num # 0 then OctOut(Dev, Num, Lev+1);
if Lev > 0 then Rem:= Rem + $80;
SetHexDigits(2);
HexOut(Dev, Rem);
ChOut(Dev, ^ );
];

\Device 8 is a circular buffer that can be written and read back.
int N;
[for N:= 0 to $40_0000 do
    [OctOut(8, N, 0);
    if N # OctIn(8) then
        [Text(0, "Error!");  exit];
    ];
OctOut(0, $1F_FFFF, 0);  CrLf(0);
OctOut(0, $20_0000, 0);  CrLf(0);
OctOut(0, $7F, 0);  CrLf(0);
OctOut(0, $4000, 0);  CrLf(0);
OctOut(0, 0, 0);  CrLf(0);
OctOut(0, $3F_FFFE, 0);  CrLf(0);
OctOut(0, $FFFF_FFFF, 0);  CrLf(0);
]


fcn to_seq(x){ //--> list of ints
   z:=(x.log2()/7);
   (0).pump(z+1,List,'wrap(j){
      x.shiftRight((z-j)*7).bitAnd(0x7f).bitOr((j!=z) and 0x80 or 0)
   });
}

fcn from_seq(in){ in.reduce(fcn(p,n){ p.shiftLeft(7).bitOr(n.bitAnd(0x7f)) },0) }


public function printArgs(... args):void
{
    for (var i:int = 0; i < args.length; i++)
        trace(args[i]);
}


with Ada.Strings.Unbounded, Ada.Text_IO;

procedure Variadic is

   subtype U_String is Ada.Strings.Unbounded.Unbounded_String;
   use type U_String;

   function "+"(S: String) return U_String
     renames Ada.Strings.Unbounded.To_Unbounded_String;

   function "-"(U: U_String) return String
     renames Ada.Strings.Unbounded.To_String;

   type Variadic_Array is array(Positive range <>) of U_String;

   procedure Print_Line(Params: Variadic_Array) is
   begin
      for I in Params'Range loop
         Ada.Text_IO.Put(-Params(I));
         if I < Params'Last then
            Ada.Text_IO.Put(" ");
         end if;
      end loop;
      Ada.Text_IO.New_Line;
   end Print_Line;

begin
   Print_Line((+"Mary", +"had", +"a", +"little", +"lamb.")); -- print five strings
   Print_Line((1 => +"Rosetta Code is cooool!")); -- print one string
end;


void
f(...)
{
    integer i;

    i = 0;
    while (i < count()) {
	o_text($i);
	o_byte('\n');
	i += 1;
    }
}

integer
main(void)
{
    f("Mary", "had", "a", "little", "lamb");

    return 0;
}


* Binary interger (H,F)
I2       DS     H          half word        2 bytes
I4       DS     F          full word        4 bytes
* Real (floating point) (E,D,L)
X4       DS     E          short            4 bytes
X8       DS     D          double           8 bytes
X16      DS     L          extended        16 bytes
* Packed decimal (P)
P3       DS     PL3                         2 bytes
P7       DS     PL7                         4 bytes
P15      DS     PL15                        8 bytes
* Zoned decimal (Z)
Z8       DS     ZL8                         8 bytes
Z16      DS     ZL16                       16 bytes
* Character (C)
C1       DS     C                           1 byte
C16      DS     CL16                       16 bytes
C256     DS     CL256                     256 bytes
* Bit value (B)
B1       DC     B'10101010'                 1 byte
* Hexadecimal value (X)
X1       DC     X'AA'                       1 byte
* Address value (A)
A4       DC     A(176)                      4 bytes   but only 3 bytes used
*                                                     (24 bits => 16 MB of storage)


MyByte:
   byte 0       ;most assemblers will also accept DB or DFB
MyWord:
   word 0       ;most assemblers will also accept DW or DFW
MyDouble:
   dd 0


main:(
  MODE STRINT = UNION(STRING, INT, PROC(REF FILE)VOID, VOID);

  PROC print strint = (FLEX[]STRINT argv)VOID: (
    FOR i TO UPB argv DO
      CASE argv[i] IN
        (INT i):print(whole(i,-1)),
        (STRING s):print(s),
        (PROC(REF FILE)VOID f):f(stand out),
        (VOID):print(error char)
      ESAC;
      IF i NE UPB argv THEN print((" ")) FI
    OD
  );

 print strint(("Mary","had",1,"little",EMPTY,new line))
)


use framework "Foundation"

-- positionalArgs :: [a] -> String
on positionalArgs(xs)

    -- follow each argument with a line feed
    map(my putStrLn, xs) as string
end positionalArgs

-- namedArgs :: Record -> String
on namedArgs(rec)
    script showKVpair
        on |λ|(k)
            my putStrLn(k & " -> " & keyValue(rec, k))
        end |λ|
    end script

    -- follow each argument name and value with line feed
    map(showKVpair, allKeys(rec)) as string
end namedArgs

-- TEST
on run
    intercalate(linefeed, ¬
        {positionalArgs(["alpha", "beta", "gamma", "delta"]), ¬
            namedArgs({epsilon:27, zeta:48, eta:81, theta:8, iota:1})})

    --> "alpha
    --   beta
    --   gamma
    --   delta
    --
    --   epsilon -> 27
    --   eta -> 81
    --   iota -> 1
    --   zeta -> 48
    --   theta -> 8
    --  "
end run

-- GENERIC FUNCTIONS

-- putStrLn :: a -> String
on putStrLn(a)
    (a as string) & linefeed
end putStrLn

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

-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
    set {dlm, my text item delimiters} to {my text item delimiters, strText}
    set strJoined to lstText as text
    set my text item delimiters to dlm
    return strJoined
end intercalate

-- allKeys :: Record -> [String]
on allKeys(rec)
    (current application's NSDictionary's dictionaryWithDictionary:rec)'s allKeys() as list
end allKeys

-- keyValue :: Record -> String -> Maybe String
on keyValue(rec, strKey)
    set ca to current application
    set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:strKey
    if v is not missing value then
        item 1 of ((ca's NSArray's arrayWithObject:v) as list)
    else
        missing value
    end if
end keyValue

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


MyByte:
   DC.B 0
   EVEN         ;you need this to prevent alignment problems if you define an odd number of bytes.
MyWord:
   DC.W 0       ;this takes up 2 bytes even though only one 0 was written
MyLong:
   DC.L 0       ;this takes up 4 bytes even though only one 0 was written


.data             ;data segment

TestValue_00 byte 0       ;an 8-bit variable
TestValue_01 word 0       ;a 16-bit variable
TestValue_02 dword 0      ;a 32-bit variable

.code

start:

mov dh, byte ptr [ds:TestValue_00]     ;load the value stored at the address "TestValue_00"
mov ax, word ptr [ds:TestValue_01]     ;load the value stored at the address "TestValue_01"


type Response is (Yes, No); -- Definition of an enumeration type with two values
for Response'Size use 1; -- Setting the size of Response to 1 bit, rather than the default single byte size


.byte 0xFF
.align 4
.word 0xFFFF
.align 4
.long 0xFFFFFFFF


10 DIM A%(10): REM the array size is 10 integers
20 DIM B(10): REM the array will hold 10 floating point values
30 DIM C$(12): REM a character array of 12 bytes


#include <boost/cstdint.hpp>

boost::int_least32_t foo;


;-------------------------------------------
; a quasi-variadic function
;-------------------------------------------
variadic: function [args][
    loop args 'arg [
        print arg
    ]
]

; calling function with one block param
; and the arguments inside

variadic ["one" 2 "three"]

;-------------------------------------------
; a function with optional attributes
;-------------------------------------------
variable: function [args][
    print ["args:" args]
    if? attr? "with" [
        print ["with:" attr "with"]
    ]
    else [
        print "without attributes"
    ]
]

variable "yes"
variable.with:"something" "yes!"


printAll(args*) {
  for k,v in args
    t .= v "`n"
  MsgBox, %t%
}


typedef long[0] zeroLength ;
writefln(zeroLength.sizeof) ; // print 0


DIM A%[10] ! the array size is 10 integers

DIM B[10]  ! the array will hold 10 floating point values

DIM C$[12] ! a character array of 12 bytes


program setsize
implicit none

  integer, parameter :: p1 = 6
  integer, parameter :: p2 = 12
  integer, parameter :: r1 = 30
  integer, parameter :: r2 = 1000
  integer, parameter :: r3 = 2
  integer, parameter :: r4 = 4
  integer, parameter :: r5 = 8
  integer, parameter :: r6 = 16
  integer, parameter :: rprec1 = selected_real_kind(p1, r1)
  integer, parameter :: rprec2 = selected_real_kind(p2, r1)
  integer, parameter :: rprec3 = selected_real_kind(p2, r2)
  integer, parameter :: iprec1 = selected_int_kind(r3)
  integer, parameter :: iprec2 = selected_int_kind(r4)
  integer, parameter :: iprec3 = selected_int_kind(r5)
  integer, parameter :: iprec4 = selected_int_kind(r6)

  real(rprec1)    :: n1
  real(rprec2)    :: n2
  real(rprec3)    :: n3
  integer(iprec1) :: n4
  integer(iprec2) :: n5
  integer(iprec3) :: n6
  integer(iprec4) :: n7
  character(30) :: form

  form = "(a7, i11, i10, i6, i9, i8)"
  write(*, "(a)") "KIND NAME   KIND NUMBER   PRECISION        RANGE "
  write(*, "(a)") "                          min   set     min     set"
  write(*, "(a)") "______________________________________________________"
  write(*, form) "rprec1", kind(n1), p1, precision(n1), r1, range(n1)
  write(*, form) "rprec2", kind(n2), p2, precision(n2), r1, range(n2)
  write(*, form) "rprec3", kind(n3), p2, precision(n3), r2, range(n3)
  write(*,*)
  form = "(a7, i11, i25, i8)"
  write(*, form) "iprec1", kind(n4), r3, range(n4)
  write(*, form) "iprec2", kind(n5), r4, range(n5)
  write(*, form) "iprec3", kind(n6), r5, range(n6)
  write(*, form) "iprec4", kind(n7), r6, range(n7)

end program


function f(a, b, c){
	if (a != "") print a
	if (b != "") print b
	if (c != "") print c
}

BEGIN {
	print "[1 arg]"; f(1)
	print "[2 args]"; f(1, 2)
	print "[3 args]"; f(1, 2, 3)
}


' Variadic functions
OPTION BASE 1
SUB demo (VAR arg$ SIZE argc)
    LOCAL x
    PRINT "Amount of incoming arguments: ", argc
    FOR x = 1 TO argc
        PRINT arg$[x]
    NEXT
END SUB

' No argument
demo(0)
' One argument
demo("abc")
' Three arguments
demo("123", "456", "789")


SUB printAll cdecl (count As Integer, ... )
    DIM arg AS Any Ptr
    DIM i   AS Integer

    arg = va_first()
    FOR i = 1 To count
        PRINT va_arg(arg, Double)
        arg = va_next(arg, Double)
    NEXT i
END SUB

printAll 3, 3.1415, 1.4142, 2.71828


package main

import (
    "fmt"
    "unsafe"
)

func main() {
    i := 5   // default type is int
    r := '5' // default type is rune (which is int32)
    f := 5.  // default type is float64
    c := 5i  // default type is complex128
    fmt.Println("i:", unsafe.Sizeof(i), "bytes")
    fmt.Println("r:", unsafe.Sizeof(r), "bytes")
    fmt.Println("f:", unsafe.Sizeof(f), "bytes")
    fmt.Println("c:", unsafe.Sizeof(c), "bytes")
    iMin := int8(5)
    rMin := byte('5')
    fMin := float32(5.)
    cMin := complex64(5i)
    fmt.Println("iMin:", unsafe.Sizeof(iMin), "bytes")
    fmt.Println("rMin:", unsafe.Sizeof(rMin), "bytes")
    fmt.Println("fMin:", unsafe.Sizeof(fMin), "bytes")
    fmt.Println("cMin:", unsafe.Sizeof(cMin), "bytes")
}


@echo off

:_main
call:_variadicfunc arg1 "arg 2" arg-3
pause>nul

:_variadicfunc
setlocal
for %%i in (%*) do echo %%~i
exit /b

:: Note: if _variadicfunc was called from cmd.exe with arguments parsed to it, it would only need to contain:
::  @for %%i in (%*) do echo %%i


/* Version a */
define f(a[], l) {
    auto i
    for (i = 0; i < l; i++) a[i]
}

/* Version b */
define g(a[]) {
    auto i
    for (i = 0; a[i] != -1; i++) a[i]
}

/* Version c */
define h(a[]) {
    auto i

    for (i = 1; i <= a[0]; i++) a[i]
}


get "libhdr"

// A, B, C, etc are dummy arguments. If more are needed, more can be added.
// Eventually you will run into the compiler limit.
let foo(num, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) be
    // The arguments can be indexed starting from the first one.
    for i=1 to num do writef("%S*N", (@num)!i)

// You can pass as many arguments as you want. The declaration above guarantees
// that at least the first 16 arguments (including the number) will be available,
// but you certainly needn't use them all.
let start() be
    foo(5, "Mary", "had", "a", "little", "lamb")


import Data.Int
import Foreign.Storable

task name value = putStrLn $ name ++ ": " ++ show (sizeOf value) ++ " byte(s)"

main = do
  let i8  = 0::Int8
  let i16 = 0::Int16
  let i32 = 0::Int32
  let i64 = 0::Int64
  let int = 0::Int
  task "Int8" i8
  task "Int16" i16
  task "Int32" i32
  task "Int64" i64
  task "Int" int


types = [Bool, Char, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64]

for t in types
    println("For type ", lpad(t,6), " size is $(sizeof(t)) 8-bit bytes, or ",
        lpad(string(8*sizeof(t)), 2), " bits.")
end

primitive type MyInt24 24 end

println("\nFor the 24-bit user defined type MyInt24, size is ", sizeof(MyInt24), " bytes.")


// version 1.0.6

fun main(args: Array<String>) {
   /* ranges for variables of the primitive numeric types */
   println("A  Byte   variable has a range of :  ${Byte.MIN_VALUE} to ${Byte.MAX_VALUE}")
   println("A  Short  variable has a range of :  ${Short.MIN_VALUE} to ${Short.MAX_VALUE}")
   println("An Int    variable has a range of :  ${Int.MIN_VALUE} to ${Int.MAX_VALUE}")
   println("A  Long   variable has a range of :  ${Long.MIN_VALUE} to ${Long.MAX_VALUE}")
   println("A  Float  variable has a range of :  ${Float.MIN_VALUE} to ${Float.MAX_VALUE}")
   println("A  Double variable has a range of :  ${Double.MIN_VALUE} to ${Double.MAX_VALUE}")
}


type
  MyBitfield = object
    flag {.bitsize:1.}: cuint


Fun1 ← •Show¨
Fun2 ← {•Show¨𝕩}
Fun3 ← { 1=≠𝕩 ? •Show 𝕩; "too many arguments " ! 𝕩}


#include <stdio.h>
#include <stdarg.h>

void varstrings(int count, ...)   /* the ellipsis indicates variable arguments */
{
    va_list args;
    va_start(args, count);
    while (count--)
        puts(va_arg(args, const char *));
    va_end(args);
}

varstrings(5, "Mary", "had", "a", "little", "lamb");


using System;

class Program {
    static void Main(string[] args) {
        PrintAll("test", "rosetta code", 123, 5.6);
    }

    static void PrintAll(params object[] varargs) {
        foreach (var i in varargs) {
            Console.WriteLine(i);
        }
    }
}


type
	correctInteger = integer attribute (size = 42);


with javascript_semantics
requires("1.0.0")
include mpfr.e
mpfr pi = mpfr_init(0,-121) -- 120 dp, +1 for the "3."
mpfr_const_pi(pi)
printf(1,"PI with 120 decimals: %s\n\n",mpfr_get_fixed(pi,120))


declare i fixed binary (7),      /* occupies  1 byte  */
        j fixed binary (15),     /* occupies  2 bytes */
        k fixed binary (31),     /* occupies  4 bytes */
        l fixed binary (63);     /* occupies  8 bytes */

declare d fixed decimal (1),     /* occupies  1 byte  */
        e fixed decimal (3),     /* occupies  2 bytes */
                                 /* an so on ...      */
        f fixed decimal (15);    /* occupies  8 bytes */

declare b(16) bit (1) unaligned; /* occupies  2 bytes */
declare c(16) bit (1) aligned;   /* occupies 16 bytes */

declare x float decimal (6),     /* occupies  4 bytes */
        y float decimal (16),    /* occupies  8 bytes */
        z float decimal (33);    /* occupies 16 bytes */


#include <iostream>

template<typename T>
 void print(T const& t)
{
  std::cout << t;
}

template<typename First, typename ... Rest>
 void print(First const& first, Rest const& ... rest)
{
  std::cout << first;
  print(rest ...);
}

int main()
{
  int i = 10;
  std::string s = "Hello world";
  print("i = ", i, " and s = \"", s, "\"\n");
}


(defn foo [& args]
  (doseq [a args]
    (println a)))

(foo :bar :baz :quux)
(apply foo [:bar :baz :quux])


EnableExplicit

Structure AllTypes
  b.b
  a.a
  w.w
  u.u
  c.c    ; character type : 1 byte on x86, 2 bytes on x64
  l.l
  i.i    ; integer type : 4 bytes on x86, 8 bytes on x64
  q.q
  f.f
  d.d
  s.s    ; pointer to string on heap : pointer size same as integer
  z.s{2} ; fixed length string of 2 characters, stored inline
EndStructure

If OpenConsole()
  Define at.AllTypes
  PrintN("Size of types in bytes (x64)")
  PrintN("")
  PrintN("byte      = " + SizeOf(at\b))
  PrintN("ascii     = " + SizeOf(at\a))
  PrintN("word      = " + SizeOf(at\w))
  PrintN("unicode   = " + SizeOf(at\u))
  PrintN("character = " + SizeOf(at\c))
  PrintN("long      = " + SizeOf(at\l))
  PrintN("integer   = " + SizeOf(at\i))
  PrintN("quod      = " + SizeOf(at\q))
  PrintN("float     = " + SizeOf(at\f))
  PrintN("double    = " + SizeOf(at\d))
  PrintN("string    = " + SizeOf(at\s))
  PrintN("string{2} = " + SizeOf(at\z))
  PrintN("---------------")
  PrintN("AllTypes  = " + SizeOf(at))
  PrintN("")
  PrintN("Press any key to close the console")
  Repeat: Delay(10) : Until Inkey() <> ""
  CloseConsole()
EndIf


       program-id. dsp-str is external.
       data division.
       linkage section.
       1 cnt comp-5 pic 9(4).
       1 str pic x.
       procedure division using by value cnt
           by reference str delimited repeated 1 to 5.
       end program dsp-str.

       program-id. variadic.
       procedure division.
           call "dsp-str" using 4 "The" "quick" "brown" "fox"
           stop run
           .
       end program variadic.

       program-id. dsp-str.
       data division.
       working-storage section.
       1 i comp-5 pic 9(4).
       1 len comp-5 pic 9(4).
       1 wk-string pic x(20).
       linkage section.
       1 cnt comp-5 pic 9(4).
       1 str1 pic x(20).
       1 str2 pic x(20).
       1 str3 pic x(20).
       1 str4 pic x(20).
       1 str5 pic x(20).
       procedure division using cnt str1 str2 str3 str4 str5.
           if cnt < 1 or > 5
               display "Invalid number of parameters"
               stop run
           end-if
           perform varying i from 1 by 1
           until i > cnt
               evaluate i
               when 1
                   unstring str1 delimited low-value
                   into wk-string count in len
               when 2
                   unstring str2 delimited low-value
                   into wk-string count in len
               when 3
                   unstring str3 delimited low-value
                   into wk-string count in len
               when 4
                   unstring str4 delimited low-value
                   into wk-string count in len
               when 5
                   unstring str5 delimited low-value
                   into wk-string count in len
               end-evaluate
               display wk-string (1:len)
           end-perform
           exit program
           .
       end program dsp-str.


(defun example (&rest args)
  (dolist (arg args)
    (print arg)))

(example "Mary" "had" "a" "little" "lamb")

(let ((args '("Mary" "had" "a" "little" "lamb")))
  (apply #'example args))


Fixpoint Arity (A B: Set) (n: nat): Set := match n with
|O => B
|S n' => A -> (Arity A B n')
end.


import std.stdio, std.algorithm;

void printAll(TyArgs...)(TyArgs args) {
    foreach (el; args)
        el.writeln;
}

// Typesafe variadic function for dynamic array
void showSum1(int[] items...) {
    items.sum.writeln;
}

// Typesafe variadic function for fixed size array
void showSum2(int[4] items...) {
    items[].sum.writeln;
}

void main() {
    printAll(4, 5.6, "Rosetta", "Code", "is", "awesome");
    writeln;
    showSum1(1, 3, 50);
    showSum2(1, 3, 50, 10);
}


/* Ranges for variables of the primitive numeric types */
println(s"A  Byte   variable has a range of :  ${Byte.MinValue} to ${Byte.MaxValue}")
println(s"A  Short  variable has a range of :  ${Short.MinValue} to ${Short.MaxValue}")
println(s"An Int    variable has a range of :  ${Int.MinValue} to ${Int.MaxValue}")
println(s"A  Long   variable has a range of :  ${Long.MinValue} to ${Long.MaxValue}")
println(s"A  Float  variable has a range of :  ${Float.MinValue} to ${Float.MaxValue}")
println(s"A  Double variable has a range of :  ${Double.MinValue} to ${Double.MaxValue}")


% proc format_trace {fmt _var el op} {upvar 1 $_var v; set v [format $fmt $v]}

% trace var foo w {format_trace %10s}
% puts "/[set foo bar]/"
/       bar/

% trace var grill w {format_trace %-10s}
% puts "/[set grill bar]/"
/bar       /


p = mpfr..pi 200               # 200 bits of precision

x = mpfr..grow(1.0E+0,1000)    # 160 default precision, grown to 1160

y = mpfr..shrink(1.0+0,40)     # 160 default shrunk to 120

z = mpfr..add(p,y)             # inherits 200 bits of precision

a = # 180 bits (not the default 160) because of more digits in the constant

1.00000000000000000000000000000000000000000000000000000E0


fn main() {
    b := true
    i := 5   // default type is i32
    r := '5'
    f := 5.0  // default type is float64
    println("b: ${sizeof(b)} bytes")
    println("i: ${sizeof(i)} bytes")
    println("r: ${sizeof(r)} bytes")
    println("f: ${sizeof(f)} bytes")
    i_min := i8(5)
    r_min := `5`
    f_min := f32(5.0)
    println("i_min: ${sizeof(i_min)} bytes")
    println("r_min: ${sizeof(r_min)} bytes")
    println("f_min: ${sizeof(f_min)} bytes")
}


func printAll(args...) {
    for i in args {
        print(i)
    }
}

printAll("test", "rosetta code", 123, 5.6)


show-all(:
    while /= ) dup:
        !.
    drop

show-all( :foo "Hello" 42 [ true ] )


// create a list with 10 elements all initialized to zero
var l = List.filled(10, 0)
// give them different values and print them
for (i in 0..9) l[i] = i
System.print(l)
// add another element to the list dynamically and print it again
l.add(10)
System.print(l)


include c:\cxpl\codes;  \intrinsic 'code' declarations
string 0;               \use zero-terminated strings
char S,
     A(1),              \sets up an array containing one byte
     B(0);              \sets up an array containing no bytes
int  I;
[S:= "";                \a zero-length (null) string
A:= Reserve(1);         \sets up a 1-byte array at runtime
B:= Reserve(0);         \sets up a 0-byte array at runtime
I:= I ! 1<<3;           \stores a single 1 bit into an integer
I:= I & ~(1<<29);       \stores a 0 bit into bit 29 of the integer
IntOut(0, I>>3 & 1);    \displays value of bit 3
]


MyByte:
   byte 0       ;most assemblers will also accept DB or DFB
MyWord:
   word 0       ;most assemblers will also accept DW or DFW
MyDouble:
   dd 0


10 DIM a$(10): REM This array will be 10 characters long
20 DIM b(10): REM this will hold a set of numbers. The fixed number of bytes per number is implementation specific
30 LET c=5: REM this is a single numerical value of fixed size


def example {
    match [`run`, args] {
        for x in args {
            println(x)
        }
    }
}

example("Mary", "had", "a", "little", "lamb")

E.call(example, "run", ["Mary", "had", "a", "little", "lamb"])


import system'routines;
import extensions;

extension variadicOp
{
    printAll(params object[] list)
    {
        for(int i := 0, i < list.Length, i+=1)
        {
            self.printLine(list[i])
        }
    }
}

public program()
{
    console.printAll("test", "rosetta code", 123, 5.6r)
}


defmodule RC do
  def print_each( arguments ) do
    Enum.each(arguments, fn x -> IO.inspect x end)
  end
end

RC.print_each([1,2,3])
RC.print_each(["Mary", "had", "a", "little", "lamb"])


(defun my-print-args (&rest arg-list)
  (message "there are %d argument(s)" (length arg-list))
  (dolist (arg arg-list)
    (message "arg is %S" arg)))

(my-print-args 1 2 3)


print_each( Arguments ) -> [io:fwrite( "~p~n", [X]) || X <- Arguments].


>function allargs () ...
$  loop 1 to argn();
$    args(#),
$  end
$endfunction
>allargs(1,3,"Test",1:2)
 1
 3
 Test
 [ 1  2 ]
>function args test (x) := {x,x^2,x^3}
>allargs(test(4))
 4
 16
 64


procedure print_args(sequence args)
    for i = 1 to length(args) do
        puts(1,args[i])
        puts(1,' ')
    end for
end procedure

print_args({"Mary", "had", "a", "little", "lamb"})


MACRO: variadic-print ( n -- quot ) [ print ] n*quot ;


program varargs

  integer, dimension(:), allocatable :: va
  integer :: i

  ! using an array (vector) static
  call v_func()
  call v_func( (/ 100 /) )
  call v_func( (/ 90, 20, 30 /) )

  ! dynamically creating an array of 5 elements
  allocate(va(5))
  va = (/ (i,i=1,5) /)
  call v_func(va)
  deallocate(va)

contains

  subroutine v_func(arglist)
    integer, dimension(:), intent(in), optional :: arglist

    integer :: i

    if ( present(arglist) ) then
       do i = lbound(arglist, 1), ubound(arglist, 1)
          print *, arglist(i)
       end do
    else
       print *, "no argument at all"
    end if
  end subroutine v_func

end program varargs


program variadicRoutinesDemo(input, output, stdErr);
{$mode objFPC}

// array of const is only supported in $mode objFPC or $mode Delphi
procedure writeLines(const arguments: array of const);
var
	argument: TVarRec;
begin
	// inside the body `array of const` is equivalent to `array of TVarRec`
	for argument in arguments do
	begin
		with argument do
		begin
			case vType of
				vtInteger:
				begin
					writeLn(vInteger);
				end;
				vtBoolean:
				begin
					writeLn(vBoolean);
				end;
				vtChar:
				begin
					writeLn(vChar);
				end;
				vtAnsiString:
				begin
					writeLn(ansiString(vAnsiString));
				end;
				// and so on
			end;
		end;
	end;
end;

begin
	writeLines([42, 'is', true, #33]);
end.


void local fn Function1( count as long, ... )
  va_list ap
  long value

  va_start( ap, count )
  while ( count )
    value = fn va_argLong( ap )
    printf @"%ld",value
    count--
  wend

  va_end( ap )
end fn

void local fn Function2( obj as CFTypeRef, ... )
  va_list ap

  va_start( ap, obj )
  while ( obj )
    printf @"%@",obj
    obj = fn va_argObj(ap)
  wend

  va_end( ap )
end fn

window 1

// params: num of args, 1st arg, 2nd arg, etc.
fn Function1( 3, 987, 654, 321 )

print

// params: 1st arg, 2nd arg, ..., NULL
fn Function2( @"One", @"Two", @"Three", @"O'Leary", NULL )

HandleEvents


func printAll(things ... string) {
  // it's as if you declared "things" as a []string, containing all the arguments
  for _, x := range things {
    fmt.Println(x)
  }
}


#!/usr/bin/env golosh
----
This module demonstrates variadic functions.
----
module Variadic

import gololang.Functions

----
Varargs have the three dots after them just like Java.
----
function varargsFunc = |args...| {
  foreach arg in args {
    println(arg)
  }
}

function main = |args| {

  varargsFunc(1, 2, 3, 4, 5, "against", "one")

  # to call a variadic function with an array we use the unary function
  unary(^varargsFunc)(args)
}


def printAll( Object[] args) { args.each{ arg -> println arg } }

printAll(1, 2, "three", ["3", "4"])


class PrintAllType t where
    process :: [String] -> t

instance PrintAllType (IO a) where
    process args = do mapM_ putStrLn args
                      return undefined

instance (Show a, PrintAllType r) => PrintAllType (a -> r) where
    process args = \a -> process (args ++ [show a])

printAll :: (PrintAllType t) => t
printAll = process []

main :: IO ()
main = do printAll 5 "Mary" "had" "a" "little" "lamb"
          printAll 4 3 5
          printAll "Rosetta" "Code" "Is" "Awesome!"


procedure main ()
  varargs("some", "extra", "args")
  write()
  varargs ! ["a","b","c","d"]
end

procedure varargs(args[])
  every write(!args)
end


printAll := method(call message arguments foreach(println))


public static void printAll(Object... things){
   // "things" is an Object[]
   for(Object i:things){
      System.out.println(i);
   }
}


function printAll() {
  for (var i=0; i<arguments.length; i++)
    print(arguments[i])
}
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!");


julia> print_each(X...) = for x in X; println(x); end

julia> print_each(1, "hello", 23.4)
1
hello
23.4


:varfunc
    1 tolist flatten
    len [
        get print nl
    ] for
    drop
;

"Enter any number of words separated by space: " input nl
stklen [split varfunc nl] if

nl "End " input


// version 1.1

fun variadic(vararg va: String) {
    for (v in va) println(v)
}

fun main(args: Array<String>) {
    variadic("First", "Second", "Third")
    println("\nEnter four strings for the function to print:")
    val va = Array(4) { "" }
    for (i in 1..4) {
        print("String $i = ")
        va[i - 1] = readLine()!!
    }
    println()
    variadic(*va)
}


#!/bin/ksh

# Variadic function

#	# Variables:
#
typeset -a arr=( 0 2 4 6 8 )

#	# Functions:
#
function _variadic {
	while [[ -n $1 ]]; do
		print $1
		shift
	done
}

 ######
# main #
 ######

_variadic Mary had a little lamb
echo
_variadic ${arr[@]}


{def foo
 {lambda {:s}
 {if {S.empty? {S.rest :s}}
  then {br}{S.first :s}
  else {br}{S.first :s} {foo {S.rest :s}}}}}

{foo hello brave new world} ->
hello
brave
new
world

{foo {S.serie 1 10}} ->
1
2
3
4
5
6
7
8
9
10


define printArgs(...items) => stdoutnl(#items)
define printEachArg(...) => with i in #rest do stdoutnl(#i)

printArgs('a', 2, (:3))
printEachArg('a', 2, (:3))


to varargs [:args]
 foreach :args [print ?]
end

(varargs "Mary "had "a "little "lamb)
apply "varargs [Mary had a little lamb]


function varar(...)
  for i, v in ipairs{...} do print(v) end
end


Module CheckIt {
      \\ Works for numbers and strings (letters in M2000)
      Function Variadic {
            \\ print a letter for each type in function stack
            Print Envelope$()
            \\Check types using Match
            Print Match("NNSNNS")
            =stack.size
            While not Empty {
                  if islet then {print letter$} else print number
            }
      }
      M=Variadic(1,2,"Hello",3,4,"Bye")
      Print M
      \\ K is a poiner to Array
      K=(1,2,"Hello 2",3,4,"Bye 2")
      \\ !K pass all items to function's stack
      M=Variadic(!K)
}
Checkit

Module CheckIt2 {
      Function Variadic {
            \\ [] return a pointer to stack, and leave a new stack as function's stack
            a=[]
            \\ a is a pointer to stack
            \\ objects just leave a space, and cursor move to next column (spread on lines)
            Print a
      }
      M=Variadic(1,2,"Hello",3,4,"Bye")
      Print M
      \\ K is a poiner to Array
      K=(1,2,"Hello 2",3,4,"Bye 2")
      \\ !K pass all items to function stack
      M=Variadic(!K)
}
Checkit2


define(`showN',
   `ifelse($1,0,`',`$2
$0(decr($1),shift(shift([email protected])))')')dnl
define(`showargs',`showN($#,[email protected])')dnl
dnl
showargs(a,b,c)
dnl
define(`x',`1,2')
define(`y',`,3,4,5')
showargs(x`'y)


ShowMultiArg[x___] := Do[Print[i], {i, {x}}]


function variadicFunction(varargin)

    for i = (1:numel(varargin))
        disp(varargin{i});
    end

end


show([L]) := block([n], n: length(L), for i from 1 thru n do disp(L[i]))$

show(1, 2, 3, 4);

apply(show, [1, 2, 3, 4]);

/* Actually, the built-in function "disp" is already what we want */
disp(1, 2, 3, 4);

apply(disp, [1, 2, 3, 4]);


def print_arg(text t) =
for x = t:
  if unknown x: message "unknown value"
  elseif numeric x: message decimal x
  elseif string x: message x
  elseif path x: message "a path"
  elseif pair x: message decimal (xpart(x)) & ", " & decimal (ypart(x))
  elseif boolean x: if x: message "true!" else: message "false!" fi
  elseif pen x: message "a pen"
  elseif picture x: message "a picture"
  elseif transform x: message "a transform" fi; endfor enddef;

print_arg("hello", x, 12, fullcircle, currentpicture, down, identity, false, pencircle);
end


MODULE Varargs EXPORTS Main;

IMPORT IO;

VAR strings := ARRAY [1..5] OF TEXT {"foo", "bar", "baz", "quux", "zeepf"};

PROCEDURE Variable(VAR arr: ARRAY OF TEXT) =
  BEGIN
    FOR i := FIRST(arr) TO LAST(arr) DO
      IO.Put(arr[i] & "\n");
    END;
  END Variable;

BEGIN
  Variable(strings);
END Varargs.


using System;
using System.Console;

module Variadic
{
    PrintAll (params args : array[object]) : void
    {
        foreach (arg in args) WriteLine(arg);
    }

    Main() : void
    {
        PrintAll("test", "rosetta code", 123, 5.6, DateTime.Now);
    }
}


proc print(xs: varargs[string, `$`]) =
  for x in xs:
    echo x


#include <stdarg.h>

void logObjects(id firstObject, ...) // <-- there is always at least one arg, "nil", so this is valid, even for "empty" list
{
  va_list args;
  va_start(args, firstObject);
  id obj;
  for (obj = firstObject; obj != nil; obj = va_arg(args, id))
    NSLog(@"%@", obj);
  va_end(args);
}

// This function can be called with any number or type of objects, as long as you terminate it with "nil":
logObjects(@"Rosetta", @"Code", @"Is", @"Awesome!", nil);
logObjects(@4, @3, @"foo", nil);


declare
  class Demo from BaseObject
     meth test(...)=Msg
        {Record.forAll Msg Show}
     end
  end

  D = {New Demo noop}
  Constructed = {List.toTuple test {List.number 1 10 1}}
in
  {D test(1 2 3 4)}
  {D Constructed}


sub print_all {
  foreach (@_) {
    print "$_\n";
  }
}


procedure print_args(sequence args)
    for i=1 to length(args) do
        ?args[i]
    end for
end procedure
print_args({"Mary", "had", "a", "little", "lamb"})


def varfunc
	1 tolist flatten
	len for
		get print nl
	endfor
enddef

"Mary" "had" "a" "little" "lamb" 5 tolist varfunc


<?php
function printAll() {
  foreach (func_get_args() as $x) // first way
    echo "$x\n";

  $numargs = func_num_args(); // second way
  for ($i = 0; $i < $numargs; $i++)
    echo func_get_arg($i), "\n";
}
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!");
?>


(de varargs @
   (while (args)
      (println (next)) ) )


/* PL/I permits optional arguments, but not an infinitely varying */
/* argument list: */
s: procedure (a, b, c, d);
   declare (a, b, c, d) float optional;
   if ^omitted(a) then put skip list (a);
   if ^omitted(b) then put skip list (b);
   if ^omitted(c) then put skip list (c);
   if ^omitted(d) then put skip list (d);
end s;


function print_all {
    foreach ($x in $args) {
        Write-Host $x
    }
}


def print_all(*things):
    for x in things:
        print x


(define varargs-func
  A -> (print A))

(define varargs
  [varargs | Args] -> [varargs-func [list | Args]]
  A -> A)

(sugar in varargs 1)


[ pack witheach
    [ echo$ cr ] ]      is counted-echo$  ( $ ... n -->   )

[ this ]                is marker         (         --> m )

[ []
  [ swap dup marker oats
   iff drop done
    nested swap join
  again ] ]             is gather         ( m x ... --> [ )

[ gather witheach
    [ echo$ cr ] ]      is markered-echo$ ( m $ ...  -->  )

$ "this" $ "is" $ "a" $ "formica" $ "table" 5 counted-echo$
cr
marker $ "green" $ "is" $ "its" $ "colour" markered-echo$


-> (define (vfun . xs) (for-each displayln xs))
-> (vfun)
-> (vfun 1)
1
-> (vfun 1 2 3 4)
1
2
3
4
-> (apply vfun (range 10 15))
10
11
12
13
14


sub foo {
   .say for @_;
   say .key, ': ', .value for %_;
}

foo 1, 2, command => 'buckle my shoe',
    3, 4, order => 'knock at the door';


SUBI printAll (...)
    FOR i = 1 TO ParamValCount
	PRINT ParamVal(i)
    NEXT i
    FOR i = 1 TO ParamStrCount
	PRINT ParamStr$(i)
    NEXT i
END SUBI

printAll 4, 3, 5, 6, 4, 3
printAll 4, 3, 5
printAll "Rosetta", "Code", "Is", "Awesome!"


Sub PrintArgs(ParamArray Args() As String)
  For i As Integer = 0 To Ubound(Args)
    Print(Args(i))
  Next
End Sub


rebol [
	Title: "Variadic Arguments"
]

print-all: func [
    args [block!] {the arguments to print}
] [
    foreach arg args [print arg]
]

print-all [rebol works this way]


print_all:  procedure              /*   [↓]     is the # of args passed.*/
                           do j=1  for arg()
                           say  arg(j)
                           end   /*j*/
return


# Project : Variadic function

sum([1,2])
sum([1,2,3])
nums = [1,2,3,4]
sum(nums)

func sum(nums)
       total = 0
       for num = 1 to len(nums)
           total = total + num
       next
       showarray(nums)
       see " " + total + nl

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


def print_all(*things)
  puts things
end


// 20220106 Rust programming solution

macro_rules! print_all {
   ($($args:expr),*) => { $( println!("{}", $args); )* }
}

fn main() {
   print_all!("Rosetta", "Code", "Is", "Awesome!");
}


def printAll(args: Any*) = args foreach println


(define (print-all . things)
    (for-each
        (lambda (x) (display x) (newline))
        things))


func print_all(*things) {
    things.each { |x| say x };
}


define: #printAll -> [| *rest | rest do: [| :arg | inform: arg printString]].

printAll applyTo: #(4 3 5 6 4 3).
printAll applyTo: #('Rosetta' 'Code' 'Is' 'Awesome!').


func printAll<T>(things: T...) {
  // "things" is a [T]
  for i in things {
    print(i)
  }
}


proc print_all {args} {puts [join $args \n]}

print_all 4 3 5 6 4 3
print_all 4 3 5
print_all Rosetta Code Is Awesome!

set things {Rosetta Code Is Awesome!}

print_all $things ;# ==> incorrect: passes a single argument (a list) to print_all
print_all {*}$things ;# ==> correct: passes each element of the list to the procedure


function printAll(separator,argv..) {
  if(argv.length)
    stdout.print(argv[0]);
  for (var i=1; i < argv.length; i++)
    stdout.print(separator, argv[i]);
}
printAll(" ", 4, 3, 5, 6, 4, 3);
printAll(",", 4, 3, 5);
printAll("! ","Rosetta", "Code", "Is", "Awesome");


Push _Mary, _had, _a, _little, _lamb   ' Push the hashes
Proc _PrintStrings (5)                 ' Print the string

Push 1, 4, 5, 19, 12, 3                ' Push the numbers
Print "Maximum is: ";FUNC(_Max(6))     ' Call the function

End

_PrintStrings Param(1)                 ' Print a variadic number of strings
  Local(1)

  For [email protected] = [email protected] To 0 Step -1           ' Reverse the hashes, load in array
    @([email protected]) = Pop()
  Next

  For [email protected] = 0 To [email protected]                   ' Now call the appropriate subroutines
    Proc @([email protected])
  Until [email protected] = [email protected]
    Print " ";                         ' Print a space
  Next                                 ' unless it is the last word

  Print                                ' Terminate the string
Return

_Max Param(1)                          ' Calculate the maximum value
  Local(3)

  [email protected] = -(2^31)                         ' Set maximum to a tiny value

  For [email protected] = 1 To [email protected]                     ' Get all values from the stack
    [email protected] = Pop()
    If [email protected] > [email protected] THEN [email protected] = [email protected]            ' Change maximum if required
  Next
Return ([email protected])                            ' Return the maximum

                                       ' Hashed labels
_Mary   Print "Mary"; : Return
_had    Print "had"; : Return
_a      Print "a"; : Return
_little Print "little"; : Return
_lamb   Print "lamb"; : Return


[myfn
   [zero? not] [swap puts pred]
   while
].

100 200 300 400 500 3 myfn


Option Explicit
'--------------------------------------------------
Sub varargs(ParamArray a())
Dim n As Long, m As Long
    Debug.Assert VarType(a) = (vbVariant Or vbArray)
    For n = LBound(a) To UBound(a)
        If IsArray(a(n)) Then
            For m = LBound(a(n)) To UBound(a(n))
                Debug.Print a(n)(m)
            Next m
        Else
            Debug.Print a(n)
        End If
    Next
End Sub
'--------------------------------------------------
Sub Main()
Dim v As Variant

    Debug.Print "call 1"
    varargs 1, 2, 3

    Debug.Print "call 2"
    varargs 4, 5, 6, 7, 8

    v = Array(9, 10, 11)
    Debug.Print "call 3"
    varargs v

    ReDim v(0 To 2)
    v(0) = 12
    v(1) = 13
    v(2) = 14
    Debug.Print "call 4"
    varargs 11, v

    Debug.Print "call 5"
    varargs v(2), v(1), v(0), 11

End Sub


fn print_all(things ...string) {
    for x in things {
        println(x)
    }
}


var printArgs = Fn.new { |args| args.each { |arg| System.print(arg) } }

printArgs.call(["Mary", "had", "3", "little", "lambs"])


(defun print-on-separate-lines (&rest xs)
    (for-each print xs))

; test the function:

(print-on-separate-lines 'i 'am 'doing 'a 'great 'work 'so 'that 'i 'cannot 'come 'down)

; to use it on a list of arguments assembled at run time, first create your list

(define test '(why should the work cease whilst i leave it and come down to you))

; and then call APPLY:

(apply print-on-separate-lines test)


include c:\cxpl\codes;          \intrinsic 'code' declarations
def IntSize=4;                  \number of bytes in an integer

proc Var(N...);                 \Display N strings passed as arguments
int  N;
[N:= Reserve(N*IntSize);        \reserve space for N string pointers
repeat  Text(0,N(0)); CrLf(0);  \display strings pointed to by N(0)
        N:= N+IntSize;          \point to next string
until   N=GetHp;                \pointing beyond reserved space?
];

Var(4, "Mary", "had", "a", "little")


Int64 i
print(T(i).size)
print(Int64.size)


package  {

    import flash.display.Sprite;
    import flash.events.Event;
    import flash.sampler.getSize;

    public class VariableSizeGet extends Sprite {

        public function VariableSizeGet() {
            if ( stage ) _init();
            else addEventListener(Event.ADDED_TO_STAGE, _init);
        }

        private function _init(e:Event = null):void {

            var i:int = 1;
            var n:Number = 0.5;
            var s:String = "abc";
            var b:Boolean = true;
            var date:Date = new Date();

            trace("An int contains " + getSize(i) + " bytes.");  // 4
            trace("A Number contains " + getSize(n) + " bytes.");  // 8
            trace("The string 'abc' contains " + getSize(s) + " bytes.");  // 24
            trace("A Boolean contains " + getSize(b) + " bytes.");  // 4
            trace("A Date object contains " + getSize(date) + " bytes.");  // 48

        }

    }

}


Int_Bits : constant Integer := Integer'size;
Whole_Bytes : constant Integer := Int_Bits / Storage_Unit; -- Storage_Unit is the number of bits per storage element


INT i; BYTES b; # typically INT and BYTES are the same size #
STRING s:="DCLXVI", [666]CHAR c;
print((
  "sizeof INT i =",bytes width, new line,
  "UPB STRING s =",UPB s, new line,
  "UPB []CHAR c =",UPB c, new line
))


VarSetCapacity(Var, 10240000)  ; allocate 10 megabytes
MsgBox % size := VarSetCapacity(Var)  ; 10240000


main:
    { (1 2 (3 4) 5 6)
    dup mu  disp
    dup nva disp
    dup npt disp
    dup nlf disp
    dup nin disp
    dup nhref disp
    dup nhword disp }

disp! : { %d cr << }


10 REM this only works with strings
20 PRINT LEN(variable$)


i = 1			#Integer
f = 1.0			#Float
s$ = "cad"		#String
dim a(99)		#Array
A = {1, 2, 3}	 	#Anonymous array
m = {"key" -> 1} 	#Map

print typeof(i)		# 1
print typeof(f)		# 2
print typeof(s$)	# 3
print typeof(A)		# 4
print typeof(m)		# 6


      DIM bstruct{b&}
      DIM istruct{i%}
      DIM fstruct{f}
      DIM dstruct{d#}
      DIM sstruct{s$}

      PRINT "Size of b& is ";DIM(bstruct{})
      PRINT "Size of i% is ";DIM(istruct{})
      PRINT "Size of f  is ";DIM(fstruct{})
      PRINT "Size of d# is ";DIM(dstruct{})
      PRINT "Size of s$ is ";DIM(sstruct{})


printf("An int contains %u bytes.\n", sizeof(int));


class Program
{
    static void Main(string[] args)
    {
        int i = sizeof(int);
        Console.WriteLine(i);
        Console.ReadLine();
    }
}


#include <cstdlib>
std::size_t intsize = sizeof(int);


       identification division.
       program-id. variable-size-get.

       environment division.
       configuration section.
       repository.
           function all intrinsic.

       data division.
       working-storage section.
       01 bc-len           constant as length of binary-char.
       01 fd-34-len        constant as length of float-decimal-34.

       77 fixed-character  pic x(13).
       77 fixed-national   pic n(13).
       77 fixed-nine       pic s9(5).
       77 fixed-separate   pic s9(5) sign trailing separate.
       77 computable-field pic s9(5) usage computational-5.
       77 formatted-field  pic +z(4),9.

       77 binary-field     usage binary-double.
       01 pointer-item     usage pointer.

       01 group-item.
          05 first-inner   pic x occurs 0 to 3 times depending on odo.
          05 second-inner  pic x occurs 0 to 5 times depending on odo-2.
       01 odo              usage index value 2.
       01 odo-2            usage index value 4.

       procedure division.
       sample-main.
       display "Size of:"
       display "BINARY-CHAR             : " bc-len
       display "  bc-len constant       : " byte-length(bc-len)
       display "FLOAT-DECIMAL-34        : " fd-34-len
       display "  fd-34-len constant    : " byte-length(fd-34-len)

       display "PIC X(13) field         : " length of fixed-character
       display "PIC N(13) field         : " length of fixed-national

       display "PIC S9(5) field         : " length of fixed-nine
       display "PIC S9(5) sign separate : " length of fixed-separate
       display "PIC S9(5) COMP-5        : " length of computable-field

       display "ALPHANUMERIC-EDITED     : " length(formatted-field)

       display "BINARY-DOUBLE field     : " byte-length(binary-field)
       display "POINTER field           : " length(pointer-item)
       >>IF P64 IS SET
       display "  sizeof(char *) > 4"
       >>ELSE
       display "  sizeof(char *) = 4"
       >>END-IF

       display "Complex ODO at 2 and 4  : " length of group-item
       set odo down by 1.
       set odo-2 up by 1.
       display "Complex ODO at 1 and 5  : " length(group-item)

       goback.
       end program variable-size-get.


(let ((a (cons 1 2))
      (b (make-array 10))
      (c "a string"))
  (list (hcl:find-object-size a)
        (hcl:find-object-size b)
        (hcl:find-object-size c)))


int i ;
writefln(i.sizeof) ;        // print 4
int[13] ints1 ;             // static integer array of length 13
writefln(ints1.sizeof) ;    // print 52
int[] ints2 = new int[13] ; // dynamic integer array, variable length, currently 13
writefln(ints2.sizeof) ;    // print 8, all dynamic array has this size
writefln(ints2.length) ;    // print 13, length is the number of allocated element in aggregated type


i := sizeof({any variable or data type identifier});


list = [1,2,3]
IO.puts length(list)                    #=> 3

tuple = {1,2,3,4}
IO.puts tuple_size(tuple)               #=> 4

string = "Elixir"
IO.puts String.length(string)           #=> 6
IO.puts byte_size(string)               #=> 6
IO.puts bit_size(string)                #=> 48

utf8 = "○×△"
IO.puts String.length(utf8)             #=> 3
IO.puts byte_size(utf8)                 #=> 8
IO.puts bit_size(utf8)                  #=> 64

bitstring = <<3 :: 2>>
IO.puts byte_size(bitstring)            #=> 1
IO.puts bit_size(bitstring)             #=> 2

map = Map.new([{:b, 1}, {:a, 2}])
IO.puts map_size(map)                   #=> 2


USING: layouts memory prettyprint ;

! Show size in bytes
{ 1 2 3 } size .   ! 48
1231298302914891021239102 size .   ! 48

! Doesn't work on fixnums and other immediate objects
10 size .   ! 0

! Show number of bits in a fixnum
fixnum-bits .   ! 60


: .CELLSIZE  ( -- ) CR 1 CELLS . ." Bytes" ;
VARIABLE X  ( creates a variable 1 cell wide)


INTEGER, PARAMETER ::  i8 = SELECTED_INT_KIND(2)
INTEGER, PARAMETER :: i16 = SELECTED_INT_KIND(4)
INTEGER, PARAMETER :: i32 = SELECTED_INT_KIND(8)
INTEGER, PARAMETER :: i64 = SELECTED_INT_KIND(16)
INTEGER(i8)  :: onebyte = 0
INTEGER(i16) :: twobytes = 0
INTEGER(i32) :: fourbytes = 0
INTEGER(i64) :: eightbytes = 0

WRITE (*,*) BIT_SIZE(onebyte), DIGITS(onebyte)             ! prints 8 and 7
WRITE (*,*) BIT_SIZE(twobytes), DIGITS(twobytes)           ! prints 16 and 15
WRITE (*,*) BIT_SIZE(fourbytes),  DIGITS(fourbytes)        ! prints 32 and 31
WRITE (*,*) BIT_SIZE(eightbytes),  DIGITS(eightbytes)      ! prints 64 and 63
WRITE (*,*) DIGITS(0.0), DIGITS(0d0)                       ! prints 24 and 53


' FB 1.05.0 Win64

Dim i As Integer
Dim l As Long
Dim s As Short
Dim b As Byte
Print "An integer occupies "; SizeOf(i); " bytes"
Print "A  long occupies    "; SizeOf(l); " bytes"
Print "A  short occupies   "; SizeOf(s); " bytes"
Print "A  byte occupies    "; SizeOf(b); " byte"

' or use type directly rather than a variable

Print "A  boolean occupies "; SizeOf(Boolean); " byte"
Print "A  single occupies  "; SizeOf(Single);  " bytes"
Print "A  double occupies  "; SizeOf(Double);  " bytes"

Print
Print "Press any key to quit"
Sleep


Public Sub Main()

Print "Boolean =\t " & SizeOf(gb.Boolean)
Print "Byte =\t\t " & SizeOf(gb.Byte)
Print "Short =\t\t " & SizeOf(gb.Short)
Print "Integer =\t " & SizeOf(gb.Integer)
Print "Single =\t " & SizeOf(gb.Single)
Print "Long =\t\t " & SizeOf(gb.Long)
Print "Float =\t\t " & SizeOf(gb.Float)
Print "Date =\t\t " & SizeOf(gb.Date)
Print "String =\t " & SizeOf(gb.String)
Print "Object =\t " & SizeOf(gb.Object)
Print "Pointer =\t " & SizeOf(gb.Pointer)
Print "Variant =\t " & SizeOf(gb.Variant)

End


import Foreign

sizeOf (undefined :: Int) -- size of Int in bytes (4 on mine)
sizeOf (undefined :: Double) -- size of Double in bytes (8 on mine)
sizeOf (undefined :: Bool) -- size of Bool in bytes (4 on mine)
sizeOf (undefined :: Ptr a) -- size of Ptr in bytes (4 on mine)


record rec0()
record rec4(a,b,c,d)

procedure main() # get size

every i := seq(1) do {
   a0 := &allocated
      x := case i of {
            1 : "ABCDEFGH"
            2 : reverse(x)
            10 : &digits
            11 : x--x
            20 : []
            21 : [1,2]
            22 : [1,2,3]
            30 : set()
            31 : set("X")
            32 : set("A","B")
            40 : table(1)
            50 : rec0()
            51 : rec4()
            60 : create seq(1)
            99 : break
            default : next
            }
   a1 := &allocated
   write("type=",type(x)," *x=",*x," bytes allocated=",a1-a0)
   }
end


arr = intarr(3,4)
print,size(arr)
;=> prints this:
       2           3           4           2          12


some_variable =: 42
7!:5<'some_variable'


julia> sizeof(Int8)
1

julia> t = 1
1

julia> sizeof(t)
8


// version 1.1.2

fun main(args: Array<String>) {
   /* sizes for variables of the primitive types (except Boolean which is JVM dependent) */
   println("A  Byte   variable occupies:  ${java.lang.Byte.SIZE / 8} byte")
   println("A  Short  variable occupies:  ${java.lang.Short.SIZE / 8} bytes")
   println("An Int    variable occupies:  ${java.lang.Integer.SIZE / 8} bytes")
   println("A  Long   variable occupies:  ${java.lang.Long.SIZE / 8} bytes")
   println("A  Float  variable occupies:  ${java.lang.Float.SIZE / 8} bytes")
   println("A  Double variable occupies:  ${java.lang.Double.SIZE / 8} bytes")
   println("A  Char   variable occupies:  ${java.lang.Character.SIZE / 8} bytes")
}


local(
	mystring	= 'Hello World',
	myarray		= array('one', 'two', 3),
	myinteger	= 1234
)

// size of a string will be a character count
#mystring -> size
'
'

// size of an array or map will be a count of elements
#myarray -> size
'
'

// elements within an array can report size
#myarray -> get(2) -> size
'
'

// integers or decimals does not have sizes
//#myinteger -> size // will fail
// an integer can however be converted to a string first
string(#myinteger) -> size


MODULE Size EXPORTS Main;

FROM IO IMPORT Put;
FROM Fmt IMPORT Int;

BEGIN
  Put("Integer in bits: " & Int(BITSIZE(INTEGER)) & "\n");
  Put("Integer in bytes: " & Int(BYTESIZE(INTEGER)) & "\n");
END Size.


echo "An int contains ", sizeof(int), " bytes."


(** The result is the size given in word.
  The word size in octet can be found with (Sys.word_size / 8).
  (The size of all the datas in OCaml is at least one word, even chars and bools.)
*)
let sizeof v =
  let rec rec_size d r =
    if List.memq r d then (1, d) else
    if not(Obj.is_block r) then (1, r::d) else
    if (Obj.tag r) = (Obj.double_tag) then (2, r::d) else
    if (Obj.tag r) = (Obj.string_tag) then (Obj.size r, r::d) else
    if (Obj.tag r) = (Obj.object_tag) ||
       (Obj.tag r) = (Obj.closure_tag)
    then invalid_arg "please only provide datas"
    else
      let len = Obj.size r in
      let rec aux d sum i =
        if i >= len then (sum, r::d) else
        let this = Obj.field r i in
        let this_size, d = rec_size d this in
        aux d (sum + this_size) (i+1)
      in
      aux d (1) 0
  in
  fst(rec_size [] (Obj.repr v))
;;


use Devel::Size qw(size total_size);

my $var = 9384752;
my @arr = (1, 2, 3, 4, 5, 6);
print size($var);         # 24
print total_size(\@arr);  # 256


printf(1,"An integer contains %d bytes.\n", machine_word())


put skip list (SIZE(x)); /* gives the number of bytes occupied by X */
                         /* whatever data type or structure it is.  */

put skip list (CURRENTSIZE(x));
                         /* gives the current number of bytes of X  */
                         /* actually used by such things as a       */
                         /* varying-length string, including its    */
                         /* length field.                           */


;;; Prints 0 because small integers need no heap storage
datasize(12) =>
;;; Prints 3: 3 character fits into single machine word, 1 word
;;; for tag, 1 for length
datasize('str') =>
;;; 3 element vector takes 5 words: 3 for values, 1 for tag, 1 for
;;; length
datasize({1 2 3}) =>
;;; Prints 3 because only first node counts
datasize([1 2 3]) =>


Define a
Debug  SizeOf(a)
; This also works for structured variables


>>> from array import array
>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'),
	('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]
>>> for typecode, initializer in argslist:
	a = array(typecode, initializer)
	print a, '\tSize =', a.buffer_info()[1] * a.itemsize
	del a

array('l') 	Size = 0
array('c', 'hello world') 	Size = 11
array('u', u'hello \u2641') 	Size = 14
array('l', [1, 2, 3, 4, 5]) 	Size = 20
array('d', [1.0, 2.0, 3.1400000000000001]) 	Size = 24
>>>


# Results are system dependent
num <- c(1, 3, 6, 10)
object.size(num)  # e.g. 56 bytes

#Allocating vectors using ':' results in less memory being (reportedly) used
num2 <- 1:4
object.size(num2) # e.g. 40 bytes

#Memory shared by objects isn't always counted
l <- list(a=c(1, 3, 6, 10), b=1:4)
object.size(l)    # e.g. 280 bytes

l2 <- list(num, num2)
object.size(l2)   # e.g. 128 bytes


#lang racket
(require ffi/unsafe)
(define-syntax-rule (sizes t ...)
  (begin (printf "sizeof(~a) = ~a\n" 't (ctype-sizeof t)) ...))
(sizes _byte _short _int _long _llong _float _double)


# Textual strings are measured in characters (graphemes)
my $string = "abc";

# Arrays are measured in elements.
say $string.chars;     # 3
my @array = 1..5;
say @array.elems;      # 5

# Buffers may be viewed either as a byte-string or as an array of elements.
my $buffer = '#56997; means "four dragons".'.encode('utf8');
say $buffer.bytes;     # 26
say $buffer.elems;     # 26


/*REXX program demonstrates  (see the penultimate statement)  how to    */
/*     to find the  size  (length)  of the value of a REXX variable.    */

/*REXX doesn't reserve any storage for any variables, as all variables  */
/*are stored as character strings, including boolean.   Storage is      */
/*obtained as necessary when REXX variables are assigned (or reassigned)*/

a = 456                                /*length of  A   is    3         */
b = "heptathlon"                       /*length of  B   is   10         */
c = "heptathlon (7 events)"            /*length of  C   is   21         */
d = ''                                 /*length of  D   is    0         */
d = ""                                 /*same as above.                 */
d = left('space junk' ,0)              /*same as above.                 */
d =                                    /*same as above.                 */
e = 99-9                               /*length of  E   is    2  (e=90) */
f = copies(a,100)                      /*length of  F   is  300  (a=456)*/
g.1 = -1                               /*length of  G.1 is    2         */
g.2 = -1.0000                          /*length of  G.2 is    7         */
                                       /*length of  HHH is    3         */

                                       /*Note that when a REXX variable */
                                       /*isn't SET, then the value of it*/
                                       /*is the uppercased name itself, */
                                       /*so in this case (upper):   HHH */

something = copies(a, random(100))     /*length is something, all right,*/
                                       /*could be 3 to 300 bytes, by gum*/
thingLen  = length(something)          /*use LENGTH bif to find its len.*/
say 'length of SOMETHING =' thingLen   /*display the length of SOMETHING*/

/*┌────────────────────────────────────────────────────────────────────┐
  │ Note that the variable's data (value) isn't the true cost of the   │
  │ size of the variable's value.  REXX also keeps the   name   of     │
  │ the (fully qualified) variable as well.                            │
  │                                                                    │
  │ Most REXX interpreters keep (at a miminum):                        │
  │                                                                    │
  │   ∙  a four-byte field which contains the length of the value      │
  │   ∙  a four-byte field which contains the length of the var name   │
  │   ∙  an   N-byte field which contains the name of the variable     │
  │   ∙  an   X-byte field which contains the variable's value         │
  │   ∙  a  one-byte field which contains the status of the variable   │
  │                                                                    │
  │ [Note that PC/REXX uses a two-byte field for the first two fields] │
  │                                                                    │
  │                                                                    │
  │ Consider the following two DO loops assigning a million variables: │
  │                                                                    │
  │                            do j=1 to 1000000                       │
  │                            integer_numbers.j=j                     │
  │                            end                                     │
  │                        ════════ and ════════                       │
  │                            do k=1 to 1000000                       │
  │                            #.k=k                                   │
  │                            end                                     │
  │                                                                    │
  │ The  "j" loop uses  35,777,792  bytes for the compound variables,  │
  │ The  "k" loop uses  21,777,792  bytes for the compound variables,  │
  │ (excluding the DO loop indices  [j and k]  themselves).            │
  └────────────────────────────────────────────────────────────────────┘*/


list1 = list(2)
list2 = list(4)
list3 = list(6)
list4 = list(7)
list5 = list(5)

see "Size of list1 is : " + len(list1) + nl
see "Size of list2 is : " + len(list2) + nl
see "Size of list3 is : " + len(list3) + nl
see "Size of list4 is : " + len(list4) + nl
see "Size of list5 is : " + len(list5) + nl


require 'objspace'

p ObjectSpace.memsize_of("a"*23)    #=> 0
p ObjectSpace.memsize_of("a"*24)    #=> 25
p ObjectSpace.memsize_of("a"*1000) #=> 1001


use std::mem;

fn main() {
    // Specify type
    assert_eq!(4, mem::size_of::<i32>());

    // Provide a value
    let arr: [u16; 3] = [1, 2, 3];
    assert_eq!(6, mem::size_of_val(&arr));
}


  def nBytes(x: Double) = ((Math.log(x) / Math.log(2) + 1e-10).round + 1) / 8

  val primitives: List[(Any, Long)] =
    List((Byte, Byte.MaxValue),
      (Short, Short.MaxValue),
      (Int, Int.MaxValue),
      (Long, Long.MaxValue))

  primitives.foreach(t => println(f"A Scala ${t._1.toString.drop(13)}%-5s has ${nBytes(t._2)} bytes"))


$$ MODE TUSCRIPT,{}
string="somerandomstring"
size=SIZE(string)
length=LENGTH(string)

PRINT "string:     ",string
PRINT "has size:   ",size
PRINT "and length: ",length


# In the shell all variables are stored as strings, so we use the same technique
# as for finding the length of a string:
greeting='Hello, world!'
greetinglength=`printf '%s' "$greeting" | wc -c`
echo "The greeting is $greetinglength characters in length"


#import std

#cast %nL

examples = <weight 'hello',mpfr..prec 1.0E+0>


void main(){
  /* you can replace the int below with any of the vala supported datatypes
     see the vala documentation for valid datatypes.
  */
  print(@"$(sizeof(int))\n");
}


print frnfn_size("uint8")		//1
print frnfn_size("int8")		//1
print frnfn_size("uint16")		//2
print frnfn_size("int16")		//2
print frnfn_size("uint32")		//4
print frnfn_size("int32")		//4
print frnfn_size("uint64")		//8
print frnfn_size("int64")		//8
print frnfn_size("float")		//4
print frnfn_size("double")		//8
print frnfn_size("char")		//1
print frnfn_size("int")			//4
print frnfn_size("short")		//2


include c:\cxpl\codes;
int  Size;
int  A, B;
real X, Y;
[Size:= addr B - addr A;
IntOut(0, Size);  CrLf(0);
Size:= addr Y - addr X;
IntOut(0, Size);  CrLf(0);
]


(123).len() //-->1 (byte)
(0).MAX.len()   //-->8 (bytes), ie the max number of bytes in an int
(1.0).MAX.len() //-->8 (bytes), ie the max number of bytes in an float
"this is a test".len() //-->14
L(1,2,3,4).len()   //-->4
Dictionary("1",1, "2",2).len() //-->2 (keys)
Data(0,Int,1,2,3,4).len() //-->4 (bytes)
Data(0,String,"1","2","3","4").len() //-->8 bytes (ASCIIZ)


BEGIN
    []INT s = ( 1, 2, 2, 3, 4, 4, 5 );
    FOR i FROM LWB s TO UPB s DO
        INT curr := s[ i ], prev;
        IF IF i > LWB s THEN curr = prev ELSE FALSE FI THEN
            print( ( i, newline ) )
        FI;
        prev := curr
    OD
END


# syntax: GAWK -f VARIABLE_DECLARATION_RESET.AWK
BEGIN {
    n = split("1,2,2,3,4,4,5",arr,",")
    for (i=1; i<=n; i++) {
      curr = arr[i]
      if (i > 1 && prev == curr) {
        printf("%s\n",i)
      }
      prev = curr
    }
    exit(0)
}


#include <stdio.h>

int main() {
    int i, gprev = 0;
    int s[7] = {1, 2, 2, 3, 4, 4, 5};

    /* There is no output as 'prev' is created anew each time
       around the loop and set explicitly to zero. */
    for (i = 0; i < 7; ++i) {
//  for (int i = 0, prev; i < 7; ++i) { // as below, see note
        int curr = s[i];
        int prev = 0;
//      int prev; // produces same output as second loop
        if (i > 0 && curr == prev) printf("%d\n", i);
        prev = curr;
    }

    /*  Now 'gprev' is used and reassigned
        each time around the loop producing the desired output. */
    for (i = 0; i < 7; ++i) {
        int curr = s[i];
        if (i > 0 && curr == gprev) printf("%d\n", i);
        gprev = curr;
    }

    return 0;
}


#include <array>
#include <iostream>

int main()
{
  constexpr std::array s {1,2,2,3,4,4,5};

  if(!s.empty())
  {
    int previousValue = s[0];

    for(size_t i = 1; i < s.size(); ++i)
    {
      // in C++, variables in block scope are reset at each iteration
      const int currentValue = s[i];

      if(i > 0 && previousValue == currentValue)
      {
        std::cout << i << "\n";
      }

      previousValue = currentValue;
    }
  }
}


// Variable declaration reset. Nigel Galloway: June 21st 2022
let s=[1;2;2;3;4;4;5]
// First let me write this in real F#, which rather avoids the whole issue
printfn "Real F#"
s|>List.pairwise|>List.iteri(fun i (n,g)->if n=g then printfn "%d" (i+1))
// Now let me take the opportunity to write some awful F# by translating the C++
printfn "C++ like awful F#"
let mutable previousValue = -1
for i in 0..s.Length-1 do
  let currentValue=s.[i]
  if previousValue = currentValue then printfn "%d" i
  previousValue <- currentValue


USING: kernel math prettyprint sequences ;

[let
    { 1 2 2 3 4 4 5 } :> s
    s length <iota> [| i |
        i s nth -1 :> ( curr prev! )
        i 0 > curr prev = and
        [ i . ] when
        curr prev!
    ] each
]


Dim As Integer s(1 To 7) => {1,2,2,3,4,4,5}
For i As Integer = 1 To Ubound(s)
    Dim As Integer curr = s(i), prev
    If i > 1 And curr = prev Then Print i
    prev = curr
Next i
Sleep


package main

import "fmt"

func main() {
    s := []int{1, 2, 2, 3, 4, 4, 5}

    // There is no output as 'prev' is created anew each time
    // around the loop and set implicitly to zero.
    for i := 0; i < len(s); i++ {
        curr := s[i]
        var prev int
        if i > 0 && curr == prev {
            fmt.Println(i)
        }
        prev = curr
    }

    // Now 'prev' is created only once and reassigned
    // each time around the loop producing the desired output.
    var prev int
    for i := 0; i < len(s); i++ {
        curr := s[i]
        if i > 0 && curr == prev {
            fmt.Println(i)
        }
        prev = curr
    }
}


public class VariableDeclarationReset {
    public static void main(String[] args) {
        int[] s = {1, 2, 2, 3, 4, 4, 5};

        // There is no output as 'prev' is created anew each time
        // around the loop and set to zero.
        for (int i = 0; i < s.length; ++i) {
            int curr = s[i];
            int prev = 0;
//          int prev; // triggers "error: variable prev might not have been initialized"
            if (i > 0 && curr == prev) System.out.println(i);
            prev = curr;
        }

        int gprev = 0;

        // Now 'gprev' is used and reassigned
        // each time around the loop producing the desired output.
        for (int i = 0; i < s.length; ++i) {
            int curr = s[i];
            if (i > 0 && curr == gprev) System.out.println(i);
            gprev = curr;
        }
    }
}


<!DOCTYPE html>
<html lang="en" >
 <head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>variable declaration reset</title>
 </head>
 <body>
  <script>
"use strict";
let s = [1, 2, 2, 3, 4, 4, 5];
for (let i=0; i<7; i+=1) {
    let curr = s[i], prev;
    if (i>0 && (curr===prev)) {
        console.log(i);
    }
    prev = curr;
}
  </script>
 </body>
</html>


s = [1, 2, 2, 3, 4, 4, 5]

for i in eachindex(s)
    curr = s[i]
    i > 1 && curr == prev && println(i)
    prev = curr
end


with javascript_semantics
sequence s = {1,2,2,3,4,4,5}
for i=1 to length(s) do
    integer curr = s[i], prev
    if i>1 and curr=prev then
        ?i
    end if
    prev = curr
end for


100H:

   /* CP/M BDOS SYSTEM CALL */
   BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5;END;
   /* CONSOLE OUTPUT ROUTINES */
   PR$CHAR:   PROCEDURE( C ); DECLARE C BYTE;    CALL BDOS( 2, C ); END;
   PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
   PR$NL:     PROCEDURE; CALL PR$STRING( .( 0DH, 0AH, '$' ) );      END;
   PR$NUMBER: PROCEDURE( N );
      DECLARE N ADDRESS;
      DECLARE V ADDRESS, N$STR( 6 ) BYTE INITIAL( '.....$' ), W BYTE;
      N$STR( W := LAST( N$STR ) - 1 ) = '0' + ( ( V := N ) MOD 10 );
      DO WHILE( ( V := V / 10 ) > 0 );
         N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      END;
      CALL PR$STRING( .N$STR( W ) );
   END PR$NUMBER;

   /* TASK */
   DECLARE S( 6 ) BYTE INITIAL( 1, 2, 2, 3, 4, 4, 5 );
   DECLARE I BYTE;
   DO I = 0 TO LAST( S );
      DO;
         DECLARE ( CURR, PREV ) BYTE;
         CURR = S( I );
         IF I > 1 AND CURR = PREV THEN DO;
            CALL PR$NUMBER( I );
            CALL PR$NL;
         END;
         PREV = CURR;
      END;
   END;

EOF


s = [1, 2, 2, 3, 4, 4, 5]

for i in range(len(s)):
    curr = s[i]
    if i > 0 and curr == prev:
        print(i)
    prev = curr


Red[]
s: [1 2 2 3 4 4 5]
repeat i length? s [
    curr: s/:i
    if all [i > 1 curr = prev][
        print i
    ]
    prev: curr
]


$ include "seed7_05.s7i";

const proc: main is func
  local
    const array integer: s is [] (1, 2, 2, 3, 4, 4, 5);
    var integer: i is 0;
    var integer: curr is 0;
    var integer: prev is 0;
  begin
    for i range 1 to length(s) do
      curr := s[i];
      if i > 1 and curr = prev then
        writeln(i);
      end if;
      prev := curr;
    end for;
  end func;


Option Strict On
Option Explicit On

Imports System.IO

Module vMain

    Public Sub Main
        Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}
        For i As Integer = 0 To Ubound(s)
            Dim curr As Integer = s(i)
            Dim prev As Integer
            If i > 1 AndAlso curr = prev Then
                  Console.Out.WriteLine(i)
            End If
            prev = curr
        Next i
    End Sub

End Module


fn main() {
    s := [1, 2, 2, 3, 4, 4, 5]

    // There is no output as 'prev' is created anew each time
    // around the loop and set implicitly to zero.
    for i := 0; i < s.len; i++ {
        curr := s[i]
        mut prev := 0
        if i > 0 && curr == prev {
            println(i)
        }
        prev = curr
    }

    // Now 'prev' is created only once and reassigned
    // each time around the loop producing the desired output.
    mut prev := 0
    for i := 0; i < s.len; i++ {
        curr := s[i]
        if i > 0 && curr == prev {
            println(i)
        }
        prev = curr
    }
}


var s = [1, 2, 2, 3, 4, 4, 5]

// There is no output as 'prev' is created anew each time
// around the loop and set implicitly to null.
for (i in 0...s.count) {
    var curr = s[i]
    var prev
    if (i > 0 && curr == prev) System.print(i)
    prev = curr
}

// Now 'prev' is created only once and reassigned
// each time around the loop producing the desired output.
var prev
for (i in 0...s.count) {
    var curr = s[i]
    if (i > 0 && curr == prev) System.print(i)
    prev = curr
}


T Vector
   Float x, y

   F (x, y)
      .x = x
      .y = y

   F +(vector)
      R Vector(.x + vector.x, .y + vector.y)

   F -(vector)
      R Vector(.x - vector.x, .y - vector.y)

   F *(mult)
      R Vector(.x * mult, .y * mult)

   F /(denom)
      R Vector(.x / denom, .y / denom)

   F String()
      R ‘(#., #.)’.format(.x, .y)

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


INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

DEFINE X_="+0"
DEFINE Y_="+6"

TYPE Vector=[CARD x1,x2,x3,y1,y2,y3]

PROC PrintVec(Vector POINTER v)
  Print("[") PrintR(v X_)
  Print(",") PrintR(v Y_) Print("]")
RETURN

PROC VecIntInit(Vector POINTER v INT ix,iy)
  IntToReal(ix,v X_)
  IntToReal(iy,v Y_)
RETURN

PROC VecRealInit(Vector POINTER v REAL POINTER rx,ry)
  RealAssign(rx,v X_)
  RealAssign(ry,v Y_)
RETURN

PROC VecStringInit(Vector POINTER v CHAR ARRAY sx,sy)
  ValR(sx,v X_)
  ValR(sy,v Y_)
RETURN

PROC VecAdd(Vector POINTER v1,v2,res)
  RealAdd(v1 X_,v2 X_,res X_) ;res.x=v1.x+v2.x
  RealAdd(v1 Y_,v2 Y_,res Y_) ;res.y=v1.y+v2.y
RETURN

PROC VecSub(Vector POINTER v1,v2,res)
  RealSub(v1 X_,v2 X_,res X_) ;res.x=v1.x-v2.x
  RealSub(v1 Y_,v2 Y_,res Y_) ;res.y=v1.y-v2.y
RETURN

PROC VecMult(Vector POINTER v REAL POINTER a Vector POINTER res)
  RealMult(v X_,a,res X_) ;res.x=v.x*a
  RealMult(v Y_,a,res Y_) ;res.y=v.y*a
RETURN

PROC VecDiv(Vector POINTER v REAL POINTER a Vector POINTER res)
  RealDiv(v X_,a,res X_) ;res.x=v.x/a
  RealDiv(v Y_,a,res Y_) ;res.y=v.y/a
RETURN

PROC Main()
  Vector v1,v2,res
  REAL s

  Put(125) PutE() ;clear the screen
  VecStringInit(v1,"12.3","-4.56")
  VecStringInit(v2,"9.87","654.3")
  ValR("0.1",s)

  VecAdd(v1,v2,res)
  PrintVec(v1) Print(" + ") PrintVec(v2)
  Print(" =") PutE() PrintVec(res) PutE() PutE()

  VecSub(v1,v2,res)
  PrintVec(v1) Print(" - ") PrintVec(v2)
  Print(" =") PutE() PrintVec(res) PutE() PutE()

  VecMult(v1,s,res)
  PrintVec(v1) Print(" * ") PrintR(s)
  Print(" = ") PrintVec(res) PutE() PutE()

  VecDiv(v1,s,res)
  PrintVec(v1) Print(" / ") PrintR(s)
  Print(" = ") PrintVec(res)
RETURN


# the standard mode COMPLEX is a two element vector #
MODE VECTOR = COMPLEX;
# the operations required for the task plus many others are provided as standard for COMPLEX and REAL items #
# the two components are fields called "re" and "im" #
# we can define a "pretty-print" operator: #
# returns a formatted representation of the vector #
OP TOSTRING = ( VECTOR a )STRING: "[" + TOSTRING re OF a + ", " + TOSTRING im OF a + "]";
# returns a formatted representation of the scaler #
OP TOSTRING = ( REAL a )STRING: fixed( a, 0, 4 );

# test the operations #
VECTOR a = 5 I 7, b = 2 I 3; # note the use of the I operator to construct a COMPLEX from two scalers #
print( ( "a+b : ", TOSTRING ( a + b  ), newline ) );
print( ( "a-b : ", TOSTRING ( a - b  ), newline ) );
print( ( "a*11: ", TOSTRING ( a * 11 ), newline ) );
print( ( "a/2 : ", TOSTRING ( a / 2  ), newline ) )


arraybase 1
dim vect1(2)
vect1[1] = 5 : vect1[2] = 7
dim vect2(2)
vect2[1] = 2 : vect2[2] = 3
dim vect3(vect1[?])

subroutine showarray(vect3)
    print "[";
    svect$ = ""
    for n = 1 to vect3[?]
        svect$ &= vect3[n] & ", "
    next n
    svect$ = left(svect$, length(svect$) - 2)
    print svect$;
    print "]"
end subroutine

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

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

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

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


#include<stdio.h>
#include<math.h>

#define pi M_PI

typedef struct{
	double x,y;
}vector;

vector initVector(double r,double theta){
	vector c;

	c.x = r*cos(theta);
	c.y = r*sin(theta);

	return c;
}

vector addVector(vector a,vector b){
	vector c;

	c.x = a.x + b.x;
	c.y = a.y + b.y;

	return c;
}

vector subtractVector(vector a,vector b){
	vector c;

	c.x = a.x - b.x;
	c.y = a.y - b.y;

	return c;
}

vector multiplyVector(vector a,double b){
	vector c;

	c.x = b*a.x;
	c.y = b*a.y;

	return c;
}

vector divideVector(vector a,double b){
	vector c;

	c.x = a.x/b;
	c.y = a.y/b;

	return c;
}

void printVector(vector a){
	printf("%lf %c %c %lf %c",a.x,140,(a.y>=0)?'+':'-',(a.y>=0)?a.y:fabs(a.y),150);
}

int main()
{
	vector a = initVector(3,pi/6);
	vector b = initVector(5,2*pi/3);

	printf("\nVector a : ");
	printVector(a);

	printf("\n\nVector b : ");
	printVector(b);

	printf("\n\nSum of vectors a and b : ");
	printVector(addVector(a,b));

	printf("\n\nDifference of vectors a and b : ");
	printVector(subtractVector(a,b));

	printf("\n\nMultiplying vector a by 3 : ");
	printVector(multiplyVector(a,3));

	printf("\n\nDividing vector b by 2.5 : ");
	printVector(divideVector(b,2.5));

	return 0;
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace RosettaVectors
{
    public class Vector
    {
        public double[] store;
        public Vector(IEnumerable<double> init)
        {
            store = init.ToArray();
        }
        public Vector(double x, double y)
        {
            store = new double[] { x, y };
        }
        static public Vector operator+(Vector v1, Vector v2)
        {
            return new Vector(v1.store.Zip(v2.store, (a, b) => a + b));
        }
        static public Vector operator -(Vector v1, Vector v2)
        {
            return new Vector(v1.store.Zip(v2.store, (a, b) => a - b));
        }
        static public Vector operator *(Vector v1, double scalar)
        {
            return new Vector(v1.store.Select(x => x * scalar));
        }
        static public Vector operator /(Vector v1, double scalar)
        {
            return new Vector(v1.store.Select(x => x / scalar));
        }
        public override string ToString()
        {
            return string.Format("[{0}]", string.Join(",", store));
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var v1 = new Vector(5, 7);
            var v2 = 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.
            var lostVector = new Vector(new double[] { 4, 8, 15, 16, 23, 42 });
            Console.WriteLine(lostVector * 7);
            Console.ReadLine();
        }
    }
}


#include <iostream>
#include <cmath>
#include <cassert>
using namespace std;

#define PI 3.14159265359

class Vector
{
public:
    Vector(double ix, double iy, char mode)
    {
        if(mode=='a')
        {
            x=ix*cos(iy);
            y=ix*sin(iy);
        }
        else
        {
            x=ix;
            y=iy;
        }
    }
    Vector(double ix,double iy)
    {
        x=ix;
        y=iy;
    }
    Vector operator+(const Vector& first)
    {
        return Vector(x+first.x,y+first.y);
    }
    Vector operator-(Vector first)
    {
        return Vector(x-first.x,y-first.y);
    }
    Vector operator*(double scalar)
    {
        return Vector(x*scalar,y*scalar);
    }
    Vector operator/(double scalar)
    {
        return Vector(x/scalar,y/scalar);
    }
    bool operator==(Vector first)
    {
        return (x==first.x&&y==first.y);
    }
    void v_print()
    {
        cout << "X: " << x << " Y: " << y;
    }
    double x,y;
};

int main()
{
    Vector vec1(0,1);
    Vector vec2(2,2);
    Vector vec3(sqrt(2),45*PI/180,'a');
    vec3.v_print();
    assert(vec1+vec2==Vector(2,3));
    assert(vec1-vec2==Vector(-2,-1));
    assert(vec1*5==Vector(0,5));
    assert(vec2/2==Vector(1,1));
    return 0;
}


% Parameterized vector class
vector = cluster [T: type] is make, add, sub, mul, div,
                              get_x, get_y, to_string
         % The inner type must support basic math
         where T has add: proctype (T,T) returns (T)
                          signals (overflow, underflow),
                     sub: proctype (T,T) returns (T)
                          signals (overflow, underflow),
                     mul: proctype (T,T) returns (T)
                          signals (overflow, underflow),
                     div: proctype (T,T) returns (T)
                          signals (zero_divide, overflow, underflow)
    rep = struct [x,y: T]

    % instantiate
    make = proc (x,y: T) returns (cvt)
        return(rep${x:x, y:y})
    end make

    % vector addition and subtraction
    add = proc (a,b: cvt) returns (cvt)
          signals (overflow, underflow)
        return(rep${x: up(a).x + up(b).x,
                    y: up(a).y + up(b).y})
        resignal overflow, underflow
    end add

    sub = proc (a,b: cvt) returns (cvt)
          signals (overflow, underflow)
        return(rep${x: up(a).x - up(b).x,
                    y: up(a).y - up(b).y})
        resignal overflow, underflow
    end sub

    % scalar multiplication and division
    mul = proc (a: cvt, b: T) returns (cvt)
          signals (overflow, underflow)
        return(rep${x: up(a).x*b, y: up(a).y*b})
        resignal overflow, underflow
    end mul

    div = proc (a: cvt, b: T) returns (cvt)
          signals (zero_divide, overflow, underflow)
        return(rep${x: up(a).x/b, y: up(a).y/b})
        resignal zero_divide, overflow, underflow
    end div

    % accessors
    get_x = proc (v: cvt) returns (T) return(v.x) end get_x
    get_y = proc (v: cvt) returns (T) return(v.y) end get_y

    % we can't just use T$unparse for pretty-printing, since
    % for floats it always prints the exponential form, and
    % that's not very pretty.
    % passing in a conversion function at the moment of
    % generating the string form is the least bad way.
    to_string = proc (v: cvt, f: proctype (T) returns (string))
                returns (string)
        return("(" || f(v.x) || ", " || f(v.y) || ")")
    end to_string
end vector

% this function formats a real somewhat neatly without needing
% extra parameters
format_real = proc (r: real) returns (string)
    return(f_form(r, 2, 4))
end format_real

start_up = proc ()
    vr = vector[real]  % use real numbers
    po: stream := stream$primary_output()

    % vectors
    a: vr := vr$make(5.0, 7.0)
    b: vr := vr$make(2.0, 3.0)

    % do some math
    a_plus_b:   vr := a + b
    a_minus_b:  vr := a - b
    a_times_11: vr := a * 11.0
    a_div_2:    vr := a / 2.0

    % show the results
    stream$putl(po, "     a = " || vr$to_string(a, format_real))
    stream$putl(po, "     b = " || vr$to_string(b, format_real))
    stream$putl(po, " a + b = " || vr$to_string(a_plus_b, format_real))
    stream$putl(po, " a - b = " || vr$to_string(a_minus_b, format_real))
    stream$putl(po, "a * 11 = " || vr$to_string(a_times_11, format_real))
    stream$putl(po, " a / 2 = " || vr$to_string(a_div_2, format_real))
end start_up


import std.stdio;

void main() {
    writeln(VectorReal(5, 7) + VectorReal(2, 3));
    writeln(VectorReal(5, 7) - VectorReal(2, 3));
    writeln(VectorReal(5, 7) * 11);
    writeln(VectorReal(5, 7) / 2);
}

alias VectorReal = Vector!real;
struct Vector(T) {
    private T x, y;

    this(T x, T y) {
        this.x = x;
        this.y = y;
    }

    auto opBinary(string op : "+")(Vector rhs) const {
        return Vector(x + rhs.x, y + rhs.y);
    }

    auto opBinary(string op : "-")(Vector rhs) const {
        return Vector(x - rhs.x, y - rhs.y);
    }

    auto opBinary(string op : "/")(T denom) const {
        return Vector(x / denom, y / denom);
    }

    auto opBinary(string op : "*")(T mult) const {
        return Vector(x * mult, y * mult);
    }

    void toString(scope void delegate(const(char)[]) sink) const {
        import std.format;
        sink.formattedWrite!"(%s, %s)"(x, y);
    }
}


program Vector;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.Math.Vectors,
  SysUtils;

procedure VectorToString(v: TVector);
begin
  WriteLn(Format('(%.1f + i%.1f)', [v.X, v.Y]));
end;

var
  a, b: TVector;

begin
  a := TVector.Create(5, 7);
  b := TVector.Create(2, 3);
  VectorToString(a + b);
  VectorToString(a - b);
  VectorToString(a * 11);
  VectorToString(a / 2);

  ReadLn;
end

.


open System

let add (ax, ay) (bx, by) =
    (ax+bx, ay+by)

let sub (ax, ay) (bx, by) =
    (ax-bx, ay-by)

let mul (ax, ay) c =
    (ax*c, ay*c)

let div (ax, ay) c =
    (ax/c, ay/c)

[<EntryPoint>]
let main _ =
    let a = (5.0, 7.0)
    let b = (2.0, 3.0)

    printfn "%A" (add a b)
    printfn "%A" (sub a b)
    printfn "%A" (mul a 11.0)
    printfn "%A" (div a 2.0)
    0 // return an integer exit code


(scratchpad) USE: math.vectors
(scratchpad) { 1 2 } { 3 4 } v+

--- Data stack:
{ 4 6 }


: v. swap . . ;
: v* swap over * >r * r> ;
: v/ swap over / >r / r> ;
: v+ >r swap >r + r> r> + ;
: v- >r swap >r - r> r> - ;


MODULE ROSETTA_VECTOR
    IMPLICIT NONE

    TYPE VECTOR
        REAL :: X, Y
    END TYPE VECTOR

    INTERFACE OPERATOR(+)
       MODULE PROCEDURE VECTOR_ADD
    END INTERFACE

    INTERFACE OPERATOR(-)
       MODULE PROCEDURE VECTOR_SUB
    END INTERFACE

    INTERFACE OPERATOR(/)
       MODULE PROCEDURE VECTOR_DIV
    END INTERFACE

    INTERFACE OPERATOR(*)
       MODULE PROCEDURE VECTOR_MULT
    END INTERFACE

    CONTAINS

    FUNCTION VECTOR_ADD(VECTOR_1, VECTOR_2)
        TYPE(VECTOR), INTENT(IN) :: VECTOR_1, VECTOR_2
        TYPE(VECTOR) :: VECTOR_ADD
        VECTOR_ADD%X = VECTOR_1%X+VECTOR_2%X
        VECTOR_ADD%Y = VECTOR_1%Y+VECTOR_2%Y
    END FUNCTION VECTOR_ADD

    FUNCTION VECTOR_SUB(VECTOR_1, VECTOR_2)
        TYPE(VECTOR), INTENT(IN) :: VECTOR_1, VECTOR_2
        TYPE(VECTOR) :: VECTOR_SUB
        VECTOR_SUB%X = VECTOR_1%X-VECTOR_2%X
        VECTOR_SUB%Y = VECTOR_1%Y-VECTOR_2%Y
    END FUNCTION VECTOR_SUB

    FUNCTION VECTOR_DIV(VEC, SCALAR)
        TYPE(VECTOR), INTENT(IN) :: VEC
        REAL, INTENT(IN) :: SCALAR
        TYPE(VECTOR) :: VECTOR_DIV
        VECTOR_DIV%X = VEC%X/SCALAR
        VECTOR_DIV%Y = VEC%Y/SCALAR
    END FUNCTION VECTOR_DIV

    FUNCTION VECTOR_MULT(VEC, SCALAR)
        TYPE(VECTOR), INTENT(IN) :: VEC
        REAL, INTENT(IN) :: SCALAR
        TYPE(VECTOR) :: VECTOR_MULT
        VECTOR_MULT%X = VEC%X*SCALAR
        VECTOR_MULT%Y = VEC%Y*SCALAR
    END FUNCTION VECTOR_MULT

    FUNCTION FROM_RTHETA(R, THETA)
        REAL :: R, THETA
        TYPE(VECTOR) :: FROM_RTHETA
        FROM_RTHETA%X = R*SIN(THETA)
        FROM_RTHETA%Y = R*COS(THETA)
    END FUNCTION FROM_RTHETA

    FUNCTION FROM_XY(X, Y)
        REAL :: X, Y
        TYPE(VECTOR) :: FROM_XY
        FROM_XY%X = X
        FROM_XY%Y = Y
    END FUNCTION FROM_XY

    FUNCTION PRETTY_PRINT(VEC)
        TYPE(VECTOR), INTENT(IN) :: VEC
        CHARACTER(LEN=100) PRETTY_PRINT
        WRITE(PRETTY_PRINT,"(A, F0.5, A, F0.5, A)") "[", VEC%X, ", ", VEC%Y, "]"
    END FUNCTION PRETTY_PRINT
END MODULE ROSETTA_VECTOR

PROGRAM VECTOR_DEMO
    USE ROSETTA_VECTOR
    IMPLICIT NONE

    TYPE(VECTOR) :: VECTOR_1, VECTOR_2
    REAL, PARAMETER :: PI = 4*ATAN(1.0)
    REAL :: SCALAR

    SCALAR = 2.0

    VECTOR_1 = FROM_XY(2.0, 3.0)
    VECTOR_2 = FROM_RTHETA(2.0, PI/6.0)

    WRITE(*,*) "VECTOR_1 (X: 2.0, Y: 3.0)      : ", PRETTY_PRINT(VECTOR_1)
    WRITE(*,*) "VECTOR_2 (R: 2.0, THETA: PI/6) : ", PRETTY_PRINT(VECTOR_2)
    WRITE(*,*) NEW_LINE('A')
    WRITE(*,*) "VECTOR_1  +  VECTOR_2          = ", PRETTY_PRINT(VECTOR_1+VECTOR_2)
    WRITE(*,*) "VECTOR_1  -  VECTOR_2          = ", PRETTY_PRINT(VECTOR_1-VECTOR_2)
    WRITE(*,*) "VECTOR_1  /  2.0               = ", PRETTY_PRINT(VECTOR_1/SCALAR)
    WRITE(*,*) "VECTOR_1  *  2.0               = ", PRETTY_PRINT(VECTOR_1*SCALAR)
END PROGRAM VECTOR_DEMO


' FB 1.05.0 Win64

Type Vector
  As Double x, y
  Declare Operator Cast() As String
End Type

Operator Vector.Cast() As String
  Return "[" + Str(x) + ", " + Str(y) + "]"
End Operator

Operator + (vec1 As Vector, vec2 As Vector) As Vector
  Return Type<Vector>(vec1.x + vec2.x, vec1.y + vec2.y)
End Operator

Operator - (vec1 As Vector, vec2 As Vector) As Vector
  Return Type<Vector>(vec1.x - vec2.x, vec1.y - vec2.y)
End Operator

Operator * (vec As Vector, scalar As Double) As Vector
  Return Type<Vector>(vec.x * scalar, vec.y * scalar)
End Operator

Operator / (vec As Vector, scalar As Double) As Vector
  ' No need to check for division by zero as we're using Doubles
  Return Type<Vector>(vec.x / scalar, vec.y / scalar)
End Operator

Dim v1 As Vector = (5, 7)
Dim v2 As Vector = (2, 3)
Print v1; " +  "; v2; " = "; v1 + v2
Print v1; " -  "; v2; " = "; v1 - v2
Print v1; " * "; 11; "     = "; v1 * 11.0
Print v1; " / ";  2; "      = "; v1 / 2.0
Print
Print "Press any key to quit"
Sleep


package main

import "fmt"

type vector []float64

func (v vector) add(v2 vector) vector {
    r := make([]float64, len(v))
    for i, vi := range v {
        r[i] = vi + v2[i]
    }
    return r
}

func (v vector) sub(v2 vector) vector {
    r := make([]float64, len(v))
    for i, vi := range v {
        r[i] = vi - v2[i]
    }
    return r
}

func (v vector) scalarMul(s float64) vector {
    r := make([]float64, len(v))
    for i, vi := range v {
        r[i] = vi * s
    }
    return r
}

func (v vector) scalarDiv(s float64) vector {
    r := make([]float64, len(v))
    for i, vi := range v {
        r[i] = vi / s
    }
    return r
}

func main() {
    v1 := vector{5, 7}
    v2 := vector{2, 3}
    fmt.Println(v1.add(v2))
    fmt.Println(v1.sub(v2))
    fmt.Println(v1.scalarMul(11))
    fmt.Println(v1.scalarDiv(2))
}


import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode
class Vector {
    private List<Number> elements
    Vector(List<Number> e ) {
        if (!e) throw new IllegalArgumentException("A Vector must have at least one element.")
        if (!e.every { it instanceof Number }) throw new IllegalArgumentException("Every element must be a number.")
        elements = [] + e
    }
    Vector(Number... e) { this(e as List) }

    def order() { elements.size() }
    def norm2() { elements.sum { it ** 2 } ** 0.5 }

    def plus(Vector that) {
        if (this.order() != that.order()) throw new IllegalArgumentException("Vectors must be conformable for addition.")
        [this.elements,that.elements].transpose()*.sum() as Vector
    }
    def minus(Vector that) { this + (-that) }
    def multiply(Number that) { this.elements.collect { it * that } as Vector }
    def div(Number that) { this * (1/that) }
    def negative() { this * -1 }

    String toString() { "(${elements.join(',')})" }
}

class VectorCategory {
   static Vector plus (Number a, Vector b) { b + a }
   static Vector minus (Number a, Vector b) { -b + a }
   static Vector multiply (Number a, Vector b) { b * a }
}


add (u,v) (x,y)      = (u+x,v+y)
minus (u,v) (x,y)    = (u-x,v-y)
multByScalar k (x,y) = (k*x,k*y)
divByScalar (x,y) k  = (x/k,y/k)

main = do
  let vecA = (3.0,8.0) -- cartersian coordinates
  let (r,theta) = (3,pi/12) :: (Double,Double)
  let vecB = (r*(cos theta),r*(sin theta)) -- from polar coordinates to cartesian coordinates
  putStrLn $ "vecA = " ++ (show vecA)
  putStrLn $ "vecB = " ++ (show vecB)
  putStrLn $ "vecA + vecB = " ++ (show.add vecA $ vecB)
  putStrLn $ "vecA - vecB = " ++ (show.minus vecA $ vecB)
  putStrLn $ "2 * vecB = " ++ (show.multByScalar 2 $ vecB)
  putStrLn $ "vecA / 3 = " ++ (show.divByScalar vecA $ 3)


import java.util.Locale;

public class Test {

    public static void main(String[] args) {
        System.out.println(new Vec2(5, 7).add(new Vec2(2, 3)));
        System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3)));
        System.out.println(new Vec2(5, 7).mult(11));
        System.out.println(new Vec2(5, 7).div(2));
    }
}

class Vec2 {
    final double x, y;

    Vec2(double x, double y) {
        this.x = x;
        this.y = y;
    }

    Vec2 add(Vec2 v) {
        return new Vec2(x + v.x, y + v.y);
    }

    Vec2 sub(Vec2 v) {
        return new Vec2(x - v.x, y - v.y);
    }

    Vec2 div(double val) {
        return new Vec2(x / val, y / val);
    }

    Vec2 mult(double val) {
        return new Vec2(x * val, y * val);
    }

    @Override
    public String toString() {
        return String.format(Locale.US, "[%s, %s]", x, y);
    }
}


def polar(r; angle):
  [ r*(angle|cos), r*(angle|sin) ];

# If your jq allows multi-arity functions, you may wish to uncomment the following line:
# def polar(r): [r, 0];

def polar2vector: polar(.[0]; .[1]);

def vector(x; y):
  if (x|type) == "number" and (y|type) == "number" then [x,y]
  else error("TypeError")
  end;

# Input: an array of same-dimensional vectors of any dimension to be added
def sum:
  def sum2: .[0] as $a | .[1] as $b | reduce range(0;$a|length) as $i ($a; .[$i] += $b[$i]);
  if length <= 1 then .
  else reduce .[1:][] as $v (.[0] ; [., $v]|sum2)
  end;

def multiply(scalar): [ .[] * scalar ];

def negate: multiply(-1);

def minus(v): [., (v|negate)] | sum;

def divide(scalar):
  if scalar == 0 then error("division of a vector by 0 is not supported")
  else [ .[] / scalar ]
  end;

def r: (.[0] | .*.) + (.[1] | .*.) | sqrt;

def atan2:
  def pi: 1 | atan * 4;
  def sign: if . < 0 then -1 elif . > 0 then 1 else 0 end;
  .[0] as $x | .[1] as $y
  | if $x == 0 then $y | sign * pi / 2
    else  ($y / $x) | if $x > 0 then atan elif . > 0 then atan - pi else atan + pi end
    end;

def angle: atan2;

def topolar: [r, angle];


module SpatialVectors

export SpatialVector

struct SpatialVector{N, T}
    coord::NTuple{N, T}
end

SpatialVector(s::NTuple{N,T}, e::NTuple{N,T}) where {N,T} =
    SpatialVector{N, T}(e .- s)
function SpatialVector(∠::T, val::T) where T
    θ = atan(∠)
    x = val * cos(θ)
    y = val * sin(θ)
    return SpatialVector((x, y))
end

angularcoef(v::SpatialVector{2, T}) where T = v.coord[2] / v.coord[1]
Base.norm(v::SpatialVector) = sqrt(sum(x -> x^2, v.coord))

function Base.show(io::IO, v::SpatialVector{2, T}) where T
    ∠ = angularcoef(v)
    val = norm(v)
    println(io, """2-dim spatial vector
        - Angular coef ∠: $(∠) (θ = $(rad2deg(atan(∠)))°)
        - Magnitude: $(val)
        - X coord: $(v.coord[1])
        - Y coord: $(v.coord[2])""")
end

Base.:-(v::SpatialVector) = SpatialVector(.- v.coord)

for op in (:+, :-)
    @eval begin
        Base.$op(a::SpatialVector{N, T}, b::SpatialVector{N, U}) where {N, T, U} =
            SpatialVector{N, promote_type(T, U)}(broadcast($op, a.coord, b.coord))
    end
end

for op in (:*, :/)
    @eval begin
        Base.$op(n::T, v::SpatialVector{N, U}) where {N, T, U} =
            SpatialVector{N, promote_type(T, U)}(broadcast($op, n, v.coord))
        Base.$op(v::SpatialVector, n::Number) = $op(n, v)
    end
end

end  # module Vectors


// version 1.1.2

class Vector2D(val x: Double, val y: Double) {
    operator fun plus(v: Vector2D) = Vector2D(x + v.x, y + v.y)

    operator fun minus(v: Vector2D) = Vector2D(x - v.x, y - v.y)

    operator fun times(s: Double) = Vector2D(s * x, s * y)

    operator fun div(s: Double) = Vector2D(x / s, y / s)

    override fun toString() = "($x, $y)"
}

operator fun Double.times(v: Vector2D) = v * this

fun main(args: Array<String>) {
    val v1 = Vector2D(5.0, 7.0)
    val v2 = Vector2D(2.0, 3.0)
    println("v1 = $v1")
    println("v2 = $v2")
    println()
    println("v1 + v2 = ${v1 + v2}")
    println("v1 - v2 = ${v1 - v2}")
    println("v1 * 11 = ${v1 * 11.0}")
    println("11 * v2 = ${11.0 * v2}")
    println("v1 / 2  = ${v1 / 2.0}")
}


vector = {mt = {}}

function vector.new (x, y)
    local new = {x = x or 0, y = y or 0}
    setmetatable(new, vector.mt)
    return new
end

function vector.mt.__add (v1, v2)
    return vector.new(v1.x + v2.x, v1.y + v2.y)
end

function vector.mt.__sub (v1, v2)
    return vector.new(v1.x - v2.x, v1.y - v2.y)
end

function vector.mt.__mul (v, s)
    return vector.new(v.x * s, v.y * s)
end

function vector.mt.__div (v, s)
    return vector.new(v.x / s, v.y / s)
end

function vector.print (vec)
    print("(" .. vec.x .. ", " .. vec.y .. ")")
end

local a, b = vector.new(5, 7), vector.new(2, 3)
vector.print(a + b)
vector.print(a - b)
vector.print(a * 11)
vector.print(a / 2)


module MyVector()
   option object;
   local value := Vector();

   export ModuleApply::static := proc( )
       Object( MyVector, _passed );
   end proc;

   export ModuleCopy::static := proc( mv::MyVector, proto::MyVector, v::Vector, $ )
   	 mv:-value := v;
   end proc;

   export ModulePrint::static := proc(mv::MyVector, $ )
       mv:-value;
   end proc;

# operations:
   export `+`::static := proc( v1::MyVector, v2::MyVector )
     MyVector( v1:-value + v2:-value );
   end proc;

   export `*`::static := proc( v::MyVector, scalar_val::numeric)
     MyVector( v:-value * scalar_val);
   end proc;

end module:


ClearAll[vector,PrintVector]
vector[{r_,\[Theta]_}]:[email protected]@AngleVector[{r,\[Theta]}]
vector[x_,y_]+vector[w_,z_]^:=vector[x+w,y+z]
a_ vector[x_,y_]^:=vector[a x,a y]
vector[x_,y_]-vector[w_,z_]^:=vector[x-w,y-z]
PrintVector[vector[x_,y_]]:=Print["vector has first component: ",x," And second component: ",y]

vector[1,2]+vector[3,4]
vector[1,2]-vector[3,4]
12vector[1,2]
vector[1,2]/3
[email protected][{Sqrt[2],45Degree}]