package require Tcl 8.5
proc tcl::mathfunc::mypow {a b} {
    if { ! [string is int -strict $b]} {error "exponent must be an integer"}
    set res 1
    for {set i 1} {$i <= $b} {incr i} {set res [expr {$res * $a}]}
    return $res
}
expr {mypow(3, 3)} ;# ==> 27
expr {mypow(3.5, 3)} ;# ==> 42.875
expr {mypow(3.5, 3.2)} ;# ==> exponent must be an integer


# these implementations ignore negative exponents
def intpow (int m, int n)
	if (< n 1)
		return 1
	end if
	decl int ret
	set ret 1
	for () (> n 0) (dec n)
		set ret (* ret m)
	end for
	return ret
end intpow

def floatpow (double m, int n)
	if (or (< n 1) (and (= m 0) (= n 0)))
		return 1
	end if
	decl int ret
	set ret 1
	for () (> n 0) (dec n)
		set ret (* ret m)
	end for
	return ret
end floatpow


Public Function exp(ByVal base As Variant, ByVal exponent As Long) As Variant
    Dim result As Variant
    If TypeName(base) = "Integer" Or TypeName(base) = "Long" Then
        'integer exponentiation
        result = 1
        If exponent < 0 Then
            result = IIf(Abs(base) <> 1, CVErr(2019), IIf(exponent Mod 2 = -1, base, 1))
        End If
        Do While exponent > 0
            If exponent Mod 2 = 1 Then result = result * base
            base = base * base
            exponent = exponent \ 2
        Loop
    Else
        Debug.Assert IsNumeric(base)
        'float exponentiation
        If base = 0 Then
            If exponent < 0 Then result = CVErr(11)
        Else
            If exponent < 0 Then
                base = 1# / base
                exponent = -exponent
            End If
            result = 1
            Do While exponent > 0
                If exponent Mod 2 = 1 Then result = result * base
                base = base * base
                exponent = exponent \ 2
            Loop
        End If
    End If
    exp = result
End Function
Public Sub main()
    Debug.Print "Integer exponentiation"
    Debug.Print "10^7=", exp(10, 7)
    Debug.Print "10^4=", exp(10, 4)
    Debug.Print "(-3)^3=", exp(-3, 3)
    Debug.Print "(-1)^(-5)=", exp(-1, -5)
    Debug.Print "10^(-1)=", exp(10, -1)
    Debug.Print "0^2=", exp(0, 2)
    Debug.Print "Float exponentiation"
    Debug.Print "10.0^(-3)=", exp(10#, -3)
    Debug.Print "10.0^(-4)=", exp(10#, -4)
    Debug.Print "(-3.0)^(-5)=", exp(-3#, -5)
    Debug.Print "(-3.0)^(-4)=", exp(-3#, -4)
    Debug.Print "0.0^(-4)=", exp(0#, -4)
End Sub


beads 1 program Factorial
//  only works for cardinal numbers 0..N
calc main_init
	log to_str(Iterative(4))  //  24
	log to_str(Recursive(5))  //  120

calc Iterative(
	n:num	--  number of iterations
	):num   --  result
	var total = 1
	loop from:2 to:n index:ix
		total = ix * total
	return total

calc Recursive ditto
	if n <= 1
		return 1
	else
		return n * Recursive(n-1)


Option Explicit

Sub Main()
Dim Primes() As Long, n As Long, temp$
Dim t As Single
    t = Timer

    n = 133218295 'limit for an Array of Longs with VBA on my computer
    Primes = ListPrimes(n)
    Debug.Print "For N = " & Format(n, "#,##0") & ", execution time : " & _
        Format(Timer - t, "0.000 s") & ", " & _
        Format(UBound(Primes) + 1, "#,##0") & " primes numbers."

    'First twenty primes
    For n = 0 To 19
        temp = temp & ", " & Primes(n)
    Next
    Debug.Print "First twenty primes : "; Mid(temp, 3)
    'Primes between 100 and 150
    n = 0: temp = vbNullString
    Do While Primes(n) < 100
        n = n + 1
    Loop
    Do While Primes(n) < 150
        temp = temp & ", " & Primes(n)
        n = n + 1
    Loop
    Debug.Print "Primes between 100 and 150 : " & Mid(temp, 3)
    'Number of primes between 7,700 and 8,000
    Dim ccount As Long
    n = 0
    Do While Primes(n) < 7700
        n = n + 1
    Loop
    Do While Primes(n) < 8000
        ccount = ccount + 1
        n = n + 1
    Loop
    Debug.Print "Number of primes between 7,700 and 8,000 : " & ccount
    'The 10 x Xth prime
    n = 1
    Do While n <= 100000
        n = n * 10
        Debug.Print "The " & n & "th prime: "; Format(Primes(n - 1), "#,##0")
    Loop
    Debug.Print "VBA has a limit in array's dim"
    Debug.Print "With my computer, the limit for an array of Long is : 133 218 295"
    Debug.Print "The last prime I could find is the : " & _
        Format(UBound(Primes), "#,##0") & "th, Value : " & _
        Format(Primes(UBound(Primes)), "#,##0")
End Sub

Function ListPrimes(MAX As Long) As Long()
Dim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long
    ReDim t(2 To MAX)
    ReDim L(MAX \ 2)
    s = Sqr(MAX)
    For i = 3 To s Step 2
        If t(i) = False Then
            For j = i * i To MAX Step i
                t(j) = True
            Next
        End If
    Next i
    L(0) = 2
    For i = 3 To MAX Step 2
        If t(i) = False Then
            c = c + 1
            L(c) = i
        End If
    Next i
    ReDim Preserve L(c)
    ListPrimes = L
End Function


uses
  System.SysUtils;

procedure runCode(code: string);
var
  c_len, i, bottles: Integer;
  accumulator: Cardinal;
begin
  c_len := Length(code);
  accumulator := 0;
  for i := 1 to c_len do
  begin
    case code[i] of
      'Q':
        writeln(code);
      'H':
        Writeln('Hello, world!');
      '9':
        begin
          bottles := 99;
          repeat
            writeln(format('%d bottles of beer on the wall', [bottles]));
            writeln(format('%d bottles of beer', [bottles]));
            Writeln('Take one down, pass it around');
            dec(bottles);
            writeln(format('%d bottles of beer on the wall' + sLineBreak, [bottles]));
          until (bottles <= 0);
        end;
      '+':
        inc(accumulator);
    end;
  end;
end;


procedure RunCode(code : String);
var
   i : Integer;
   accum, bottles : Integer;
begin
   for i:=1 to Length(code) do begin
      case code[i] of
         'Q', 'q' : PrintLn(code);
         'H', 'h' : PrintLn('Hello, world!');
         '9' : begin
            bottles:=99;
            while bottles>1 do begin
               Print(bottles); PrintLn(' bottles of beer on the wall,');
               Print(bottles); PrintLn(' bottles of beer.');
               PrintLn('Take one down, pass it around,');
               Dec(bottles);
               if bottles>1 then begin
                  Print(bottles); PrintLn(' bottles of beer on the wall.'#13#10);
               end;
            end;
            PrintLn('1 bottle of beer on the wall.');
         end;
         '+' : Inc(accum);
      else
         PrintLn('Syntax Error');
      end;
   end;
end;


HailStone := Object clone
HailStone sequence := method(n,
    if(n < 1, Exception raise("hailstone: expect n >= 1 not #{n}" interpolate))
    n = n floor         // make sure integer value
    stones := list(n)
    while (n != 1,
        n = if(n isEven, n/2, 3*n + 1)
        stones append(n)
    )
    stones
)

if( isLaunchScript,
    out := HailStone sequence(27)
    writeln("hailstone(27) has length ",out size,": ",
        out slice(0,4) join(" ")," ... ",out slice(-4) join(" "))

    maxSize := 0
    maxN := 0
    for(n, 1, 100000-1,
        out = HailStone sequence(n)
        if(out size > maxSize,
            maxSize = out size
            maxN = n
        )
    )

    writeln("For numbers < 100,000, ", maxN,
    " has the longest sequence of ", maxSize, " elements.")
)


hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"0
9!:29]1
9!:27'main 0'
main=:3 :0
  smoutput 'Hailstone sequence for the number 27'
  smoutput hailseq 27
  smoutput ''
  smoutput 'Finding number with longest hailstone sequence which is'
  smoutput 'less than 100000 (and finding that sequence length):'
  smoutput ([email protected](= >./),>./) #@hailseq i.1e5
)


import java.util.ArrayList;
import java.util.List;

//  task 1
public class HailstoneSequence {

    public static void main(String[] args) {
        //  task 2
        int n = 27;
        List<Long> sequence27 = hailstoneSequence(n);
        System.out.printf("Hailstone sequence for %d has a length of %d:%nhailstone(%d) = %s%n", n, sequence27.size(), n, sequence27);

        //  task 3
        int maxN = 0;
        int maxLength = 0;
        for ( int i = 1 ; i < 100_000 ; i++ ) {
            int seqLength = hailstoneSequence(i).size();
            if ( seqLength > maxLength ) {
                maxLength = seqLength;
                maxN = i;
            }
        }
        System.out.printf("Longest hailstone sequence less than 100,000: hailstone(%d).length() = %d", maxN, maxLength);
    }

    public static List<Long> hailstoneSequence(long n) {
        if ( n <= 0 ) {
            throw new IllegalArgumentException("Must be grater than or equal to zero.");
        }
        List<Long> sequence = new ArrayList<>();
        sequence.add(n);
        while ( n > 1 ) {
            if ( (n & 1) == 0 ) {
                n /= 2;
            }
            else {
                n = 3 * n + 1;
            }
            sequence.add(n);
        }
        return sequence;
    }

}


with POSIX.Unsafe_Process_Primitives;

procedure Execute_A_System_Command is
   Arguments : POSIX.POSIX_String_List;
begin
   POSIX.Append (Arguments, "ls");
   POSIX.Unsafe_Process_Primitives.Exec_Search ("ls", Arguments);
end Execute_A_System_Command;


var lines = system ("ls")
foreach line lines {
    println (line)
}


sshell ss;

ss.argv.insert("ls");

o_(ss.link);


#!/usr/bin/hopper

#include <hopper.h>

main:

  /* execute "ls -lstar" with no result return (only displayed) */
  {"ls -lstar"},execv

  /* this form does not allow composition of the line with variables.
     Save result in the variable "s", and then display it */
  s=`ls -l | awk '{if($2=="2")print $0;}'`
  {"\n",s,"\n"}print

  data="2"
  {""}tok sep

  // the same as above, only I can compose the line:
  {"ls -l | awk '{if($2==\"",data,"\")print $0;}'"}join(s),{s}exec,print
  {"\n\n"}print

  // this does the same as above, with an "execute" macro inside a "let" macro:
  t=0,let (t := execute( {"ls -l | awk '{if($2==\""},{data},{"\")print $0;}'"} ))
  {t,"\n"}print

{0}return


- fib(n : UINTEGER_32) : UINTEGER_64 <- (
  + result : UINTEGER_64;
  (n < 2).if {
    result := n;
  } else {
    result := fib(n - 1) + fib(n - 2);
  };
  result
);


Function pow(x,y)
	pow = 1
	If y < 0 Then
		For i = 1 To Abs(y)
			pow = pow * (1/x)
		Next
	Else
		For i = 1 To y
			pow = pow * x
		Next
	End If
End Function

WScript.StdOut.Write "2 ^ 0 = " & pow(2,0)
WScript.StdOut.WriteLine
WScript.StdOut.Write "7 ^ 6 = " & pow(7,6)
WScript.StdOut.WriteLine
WScript.StdOut.Write "3.14159265359 ^ 9 = " & pow(3.14159265359,9)
WScript.StdOut.WriteLine
WScript.StdOut.Write "4 ^ -6 = " & pow(4,-6)
WScript.StdOut.WriteLine
WScript.StdOut.Write "-3 ^ 5 = " & pow(-3,5)
WScript.StdOut.WriteLine


include c:\cxpl\codes;  \intrinsic 'code' declarations

func real Power(X, Y);  \X raised to the Y power; (X > 0.0)
real X;  int Y;
return Exp(float(Y) * Ln(X));

func IPower(X, Y);      \X raised to the Y power
int  X, Y;
int  P;
[P:= 1;
while Y do
    [if Y&1 then P:= P*X;
    X:= X*X;
    Y:= Y>>1;
    ];
return P;
];

int X, Y;
[Format(9, 0);
for X:= 1 to 10 do
    [for Y:= 0 to 7 do
        RlOut(0, Power(float(X), Y));
    CrLf(0);
    ];
CrLf(0);
for X:= 1 to 10 do
    [for Y:= 0 to 7 do
        [ChOut(0, 9);  IntOut(0, IPower(X, Y))];
    CrLf(0);
    ];
]


class Num2 {
    static ipow(i, exp) {
        if (!i.isInteger) Fiber.abort("ipow method must have an integer receiver")
        if (!exp.isInteger) Fiber.abort("ipow method must have an integer exponent")
        if (i == 1 || exp == 0) return 1
        if (i == -1) return (exp%2 == 0) ? 1 : -1
        if (exp < 0) Fiber.abort("ipow method cannot have a negative exponent")
        var ans = 1
        var base = i
        var e = exp
        while (e > 1) {
            if (e%2 == 1) ans = ans * base
            e = (e/2).floor
            base = base * base
        }
        return ans * base
    }

    static fpow(f, exp) {
        if (!exp.isInteger) Fiber.abort("fpow method must have an integer exponent")
        var ans = 1.0
        var e = exp
        var base = (e < 0) ? 1/f : f
        if (e < 0) e = -e
        while (e > 0) {
            if (e%2 == 1) ans = ans * base
            e = (e/2).floor
            base = base * base
        }
        return ans
    }

    construct new(n) { _n = n }

    ^(exp) {
        if (_n.isInteger && (exp >= 0 || _n.abs == 1)) return Num2.ipow(_n, exp)
        return Num2.fpow(_n, exp)
    }
}

System.print("Using static methods:")
System.print("  2  ^  3   = %(Num2.ipow(2, 3))")
System.print("  1  ^ -10  = %(Num2.ipow(1, -10))")
System.print(" -1  ^ -3   = %(Num2.ipow(-1, -3))")
System.print()
System.print("  2.0 ^ -3  = %(Num2.fpow(2.0, -3))")
System.print("  1.5 ^  0  = %(Num2.fpow(1.5, 0))")
System.print("  4.5 ^  2  = %(Num2.fpow(4.5, 2))")

System.print("\nUsing the ^ operator:")
System.print("  2  ^  3   = %(Num2.new(2) ^ 3)")
System.print("  1  ^ -10  = %(Num2.new(1) ^ -10)")
System.print(" -1  ^ -3   = %(Num2.new(-1) ^ -3)")
System.print()
System.print("  2.0 ^ -3  = %(Num2.new(2.0) ^ -3)")
System.print("  1.5 ^  0  = %(Num2.new(1.5) ^ 0)")
System.print("  4.5 ^  2  = %(Num2.new(4.5) ^ 2)")


import "/fmt" for Fmt

var primeSieve = Fn.new { |limit|
    if (limit < 2) return []
    var c = [false] * (limit + 1) // composite = true
    c[0] = true
    c[1] = true
    // no need to process the even numbers > 2
    var k = 9
    while (k <= limit) {
        c[k] = true
        k = k + 6
    }
    k = 25
    while (k <= limit) {
        c[k] = true
        k = k + 10
    }
    k = 49
    while (k <= limit) {
        c[k] = true
        k = k + 14
    }
    var p = 11
    var p2 = 121
    var inc = [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,
        4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10]
    var w = 0
    while (p2 <= limit) {
        var i = p2
        while (i <= limit) {
            c[i] = true
            i = i + 2*p
        }
        var ok = true
        while (ok) {
            p = p + inc[w]
            w = (w + 1) % 48
            ok = c[p]
        }
        p2 = p * p
    }
    var primes = [2]
    var i = 3
    while (i <= limit) {
        if (!c[i]) primes.add(i)
        i = i + 2
    }
    return primes
}

var primes = primeSieve.call(1e8 * 2)
System.print("The first 20 primes are: ")
System.print(primes.take(20).toList)
System.print("\nThe primes between 100 and 150 are:")
System.print(primes.where { |p| p > 100 && p < 150 }.toList)
System.write("\nThe number of primes between 7,700 and 8,000 is: ")
Fmt.print("$,d", primes.count{ |p| p > 7700 && p < 8000 })
Fmt.print("\nThe 10,000th prime is: $,d",  primes[9999])
Fmt.print("\nThe 100,000th prime is: $,d", primes[99999])
Fmt.print("\nThe 1,000,000th prime is: $,d", primes[999999])


func eval(code) {
    var accumulator = 0
    var opcodes = (
        "h": () => print("Hello, World!"),
        "q": () => print(code),
        "9": () => {
                var quantity = 99
                while quantity > 1 {
                    print("\(quantity) bottles of beer on the wall, \(quantity) bottles of beer.")
                    print("Take one down and pass it around, \(quantity - 1) bottles of beer.")
                    quantity -= 1
                }
                print("1 bottle of beer on the wall, 1 bottle of beer.")
                print("Take one down and pass it around, no more bottles of beer on the wall.\n")
                print("No more bottles of beer on the wall, no more bottles of beer.")
                print("Go to the store and buy some more, 99 bottles of beer on the wall.")
            },
        "+": () => { accumulator += 1 }
    )

    for c in code {
        opcodes[c.Lower()]()
    }
}


open unsafe.console char unsafe.cell imperative

eval src = eval' src
     where eval' [] = ()
           eval' (x::xs) | be 'H' = h() `seq` eval' xs
                         | be 'Q' = q() `seq` eval' xs
                         | be '9' = n() `seq` eval' xs
                         | be '+' = p() `seq` eval' xs
                         | else = fail ("Unrecognized " ++ x)
                         where r = ref 0
                               be c = char.upper x == c
                               h () = writen "Hello, world!"
                               q () = writen src
                               p () = r.+
                               n () = bottles [99,98..1]
                                  where bottles [] = ()
                                        bottles (x::xs) = rec write
                                          (show x) " bottles of beer of the wall\r\n"
                                          (show x) " bottles of beer\r\n"
                                          "Take one down, pass it around\r\n"
                                          `seq` bottles xs


% hq9+ Erlang implementation (JWL)
% http://www.erlang.org/
-module(hq9p).
-export([main/1]).

%% bottle helper routine
bottle(0) ->
  io:format("No more bottles of beer ");

bottle(1) ->
  io:format("1 bottle of beer ");

bottle(N) when N > 0 ->
  io:format("~w bottles of beer ", [N]).

%% Implementation of instructions
beer(0) ->
  bottle(0), io:format("on the wall~n"),
  bottle(0), io:format("on the wall~nGo to the store and buy some more~n"),
  io:format("99 bottles of beer on the wall.~n");

beer(N) ->
  bottle(N), io:format("on the wall~n"),
  bottle(N), io:format("~nTake one down and pass it around~n"),
  bottle(N-1), io:format("on the wall~n~n"),
  beer(N-1).

hello() ->
  io:format("Hello world!~n", []).

prog(Prog) ->
  io:format("~s~n", [Prog]).

inc(Acc) ->
  Acc+1.

%% Interpreter
execute(Instruction, Prog, Acc) ->
  case Instruction of
    $H -> hello(), Acc;
    $Q -> prog(Prog), Acc;
    $9 -> beer(99), Acc;
    $+ -> inc(Acc);
       _ -> io:format("Invalid instruction: ~c~n", [Instruction]), Acc
  end.

main([], _Prog, Acc) ->
  Acc;

main([Instruction | Rest], Prog, Acc) ->
  NewAcc = execute(Instruction, Prog, Acc),
  main(Rest, Prog, NewAcc).

main(Prog) ->
  Compiled = string:to_upper(Prog),
  main(Compiled, Prog, 0).


############### in file hailstone.jl ###############
module Hailstone

function hailstone(n)
    ret = [n]
    while n > 1
        if n & 1 > 0
            n = 3n + 1
        else
            n = Int(n//2)
        end
        append!(ret, n)
    end
    return ret
end

export hailstone

end

if PROGRAM_FILE == "hailstone.jl"
    using Hailstone
    h = hailstone(27)
    n = length(h)
    println("The sequence of hailstone(27) is:\n $h.\nThis sequence is of length $n. It starts with $(h[1:4]) and ends with $(h[n-3:end]).")
end
############ in file moduletest.jl ####################
include("hailstone.jl")
using Hailstone
function countstones(mi, mx)
    lengths2occurences = Dict()
    mostfreq = mi
    maxcount = 1
    for i in mi:mx
        h = hailstone(i)
        n = length(h)
        if haskey(lengths2occurences, n)
            newoccurences = lengths2occurences[n] + 1
            if newoccurences > maxcount
                maxcount = newoccurences
                mostfreq = n
            end
            lengths2occurences[n] = newoccurences
        else
            lengths2occurences[n] = 1
        end
    end
    mostfreq, maxcount
end

nlen, cnt = countstones(1,99999)

print("The most common hailstone sequence length for hailstone(n) for 1 <= n < 100000 is $nlen, which occurs $cnt times.")


implement Execlib;

include "sys.m"; sys: Sys;
include "draw.m";

Execlib: module {
	init: fn(ctxt: ref Draw->Context, args: list of string);
	hailstone: fn(i: big): list of big;
};

init(nil: ref Draw->Context, nil: list of string)
{
	sys = load Sys Sys->PATH;

	seq := hailstone(big 27);
	l := len seq;

	sys->print("hailstone(27):  ");
	for(i := 0; i < 4; i++) {
		sys->print("%bd, ", hd seq);
		seq = tl seq;
	}
	sys->print("⋯");

	while(len seq > 4)
		seq = tl seq;

	while(seq != nil) {
		sys->print(", %bd", hd seq);
		seq = tl seq;
	}
	sys->print(" (length %d)\n", l);

	max := 1;
	maxn := big 1;
	for(n := big 2; n < big 100000; n++) {
		cur := len hailstone(n);
		if(cur > max) {
			max = cur;
			maxn = n;
		}
	}
	sys->print("hailstone(%bd) has length %d\n", maxn, max);
}

hailstone(i: big): list of big
{
	if(i == big 1)
		return big 1 :: nil;
	if(i % big 2 == big 0)
		return i :: hailstone(i / big 2);
	return i :: hailstone(big 3 * i + big 1);
}


#!/usr/bin/env luajit
bit32=bit32 or bit
local lib={
	hailstone=function(n)
		local seq={n}
		while n>1 do
			n=bit32.band(n,1)==1 and 3*n+1 or n/2
			seq[#seq+1]=n
		end
		return seq
	end
}

if arg[0] and arg[0]:match("hailstone.lua") then
	local function printf(fmt, ...) io.write(string.format(fmt, ...)) end
	local seq=lib.hailstone(27)
	printf("27 has %d numbers in sequence:\n",#seq)
	for _,i in ipairs(seq) do
		printf("%d ", i)
	end
	printf("\n")
else
	return lib
end


      h ← ⎕fio['fork_daemon'] '/bin/ls /var'
      backups  games     lib    lock  mail  run    tmp
cache    gemini  local  log   opt   spool
      ⎕fio['fclose'] h
0


do shell script "ls" without altering line endings


-- Iterative, translation of the basic version.
function fibi n
    put 0 into aa
    put 1 into b
    repeat with i = 1 to n
        put aa + b into temp
        put b into aa
        put temp into b
    end repeat
    return aa
end fibi

-- Recursive
function fibr n
     if n <= 1 then
        return n
    else
        return fibr(n-1) + fibr(n-2)
    end if
end fibr


fcn pow(n,exp){
   reg v;
   if(n.isType(1)){ // Int
      if (exp<0) return(if(n*n!=1) 0 else (if(exp.isOdd) n else 1));
      v=1;
   }else{
      if(exp<0){ n=1.0/n; exp=-exp; }
      v=1.0;
   }
   while(exp>0){
      if(exp.isOdd) v*=n;
      n*=n;
      exp/=2;
   }
   v
}


const std = @import("std");
const builtin = std.builtin;
const heap = std.heap;
const mem = std.mem;
const meta = std.meta;

fn assertInt(comptime T: type) builtin.TypeInfo.Int {
    if (@typeInfo(T) != .Int)
        @compileError("data type must be an integer.");
    const int = @typeInfo(T).Int;
    if (int.is_signed == true or int.bits % 2 == 1 or int.bits < 4)
        @compileError("type must be an unsigned integer with even bit size (of at least 4 bits).");
    return int;
}

fn sqrtType(comptime T: type) type {
    const t = assertInt(T);
    return meta.Int(.unsigned, t.bits / 2);
}

// given an upper bound, max, return the most restrictive sieving data type.
pub fn autoSieveType(comptime max: u64) type {
    if (max == 0)
        @compileError("The maximum sieving size must be non-zero.");
    var bit_len = 64 - @clz(u64, max);
    if (max & (max - 1) == 0) // power of two
        bit_len -= 1;
    if (bit_len % 2 == 1)
        bit_len += 1;
    if (bit_len < 4)
        bit_len = 4;
    return meta.Int(.unsigned, bit_len);
}

test "type meta functions" {
    const expect = std.testing.expect;
    expect(sqrtType(u20) == u10);
    expect(autoSieveType(8000) == u14);
    expect(autoSieveType(9000) == u14);
    expect(autoSieveType(16384) == u14);
    expect(autoSieveType(16385) == u16);
    expect(autoSieveType(32768) == u16);
    expect(autoSieveType(1000) == u10);
    expect(autoSieveType(10) == u4);
    expect(autoSieveType(4) == u4);
    expect(autoSieveType(std.math.maxInt(u32)) == u32);
}

const wheel2357 = [48]u8{
    10, 2, 4, 2, 4, 6, 2,  6,
    4,  2, 4, 6, 6, 2, 6,  4,
    2,  6, 4, 6, 8, 4, 2,  4,
    2,  4, 8, 6, 4, 6, 2,  4,
    6,  2, 6, 6, 4, 2, 4,  6,
    2,  6, 4, 2, 4, 2, 10, 2,
};

fn Wheel2357Multiple(comptime Int: type) type {
    _ = assertInt(Int);
    return struct {
        multiple: Int,
        base_prime: Int,
        offset: u6,

        fn less(self: Wheel2357Multiple(Int), other: Wheel2357Multiple(Int)) bool {
            return self.multiple < other.multiple;
        }
    };
}

pub fn PrimeGen(comptime Int: type) type {
    _ = assertInt(Int);
    return struct {
        const Self = @This();

        initial_primes: u16,
        offset: u6,
        candidate: Int,
        multiples: std.PriorityQueue(Wheel2357Multiple(Int)),
        allocator: *mem.Allocator,
        count: u32,

        pub fn init(alloc: *mem.Allocator) Self {
            return Self{
                .initial_primes = 0xAC, // primes 2, 3, 5, 7 in a bitmask
                .offset = 0,
                .candidate = 1,
                .count = 0,
                .allocator = alloc,
                .multiples = std.PriorityQueue(Wheel2357Multiple(Int)).init(alloc, Wheel2357Multiple(Int).less),
            };
        }

        pub fn deinit(self: *PrimeGen(Int)) void {
            self.multiples.deinit();
        }

        pub fn next(self: *PrimeGen(Int)) !?Int {
            if (self.initial_primes != 0) { // use the bitmask up first
                const p = @as(Int, @ctz(u16, self.initial_primes));
                self.initial_primes &= self.initial_primes - 1;
                self.count += 1;
                return p;
            } else {
                while (true) {
                    // advance to the next prime candidate.
                    if (@addWithOverflow(Int, self.candidate, wheel2357[self.offset], &self.candidate))
                        return null;
                    self.offset = (self.offset + 1) % @as(u6, wheel2357.len);

                    // See if the composite number on top of the heap matches
                    // the candidate.
                    //
                    var top = self.multiples.peek();
                    if (top == null or self.candidate < top.?.multiple) {
                        // prime found, add the square and it's position on the wheel
                        // to the heap.
                        //
                        if (self.candidate <= std.math.maxInt(sqrtType(Int)))
                            try self.multiples.add(Wheel2357Multiple(Int){
                                .multiple = self.candidate * self.candidate,
                                .base_prime = self.candidate,
                                .offset = self.offset,
                            });
                        self.count += 1;
                        return self.candidate;
                    } else {
                        while (true) {
                            // advance the top of heap to the next prime multiple
                            // that is not a multiple of 2, 3, 5, 7.
                            //
                            var mult = self.multiples.remove();
                            // If the multiple becomes too big (greater than the the maximum
                            // sieve size), then there's no reason to add it back to the queue.
                            //
                            var tmp: Int = undefined;
                            if ([email protected](Int, mult.base_prime, wheel2357[mult.offset], &tmp) and
                                [email protected](Int, tmp, mult.multiple, &mult.multiple))
                            {
                                mult.offset = (mult.offset + 1) % @as(u6, wheel2357.len);
                                try self.multiples.add(mult);
                            }
                            top = self.multiples.peek();
                            if (top == null or self.candidate != top.?.multiple)
                                break;
                        }
                    }
                }
            }
        }
    };
}


// http://stackoverflow.com/revisions/10733621/4

fcn postponed_sieve(){            # postponed sieve, by Will Ness
   vm.yield(2); vm.yield(3);	  # original code David Eppstein,
   vm.yield(5); vm.yield(7);      #        ActiveState Recipe 2002
   D:=Dictionary();
   ps:=Utils.Generator(postponed_sieve);  # a separate Primes Supply:
   p:=ps.pump(2,Void);            # (3) a Prime to add to dict
   q:=p*p;                        # (9) when its sQuare is
   c:=9;                          # the next Candidate
   while(1){
      if (not D.holds(c)){        # not a multiple of any prime seen so far:
         if (c < q) vm.yield(c);  #   a prime, or
	 else{   # (c==q):        #   the next prime's square:
            add(D,c + 2*p,2*p);   #     (9+6,6 : 15,21,27,33,...)
	    p=ps.next();          #     (5)
	    q=p*p;                #     (25)
	 }
      }else{                      # 'c' is a composite:
	 s := D.pop(c);           #   step of increment
	 add(D,c + s,s);          #   next multiple, same step
      }
      c += 2;                     # next odd candidate
   }
}

fcn add(D,x,s){                   # make no multiple keys in Dict
   while(D.holds(x)){ x += s }    # increment by the given step
   D[x] = s;
}


USING: combinators command-line formatting interpolate io kernel
math math.ranges multiline namespaces sequences ;
IN: rosetta-code.hq9+

STRING: verse
${3} bottle${1} of beer on the wall
${3} bottle${1} of beer
Take one down, pass it around
${2} bottle${0} of beer on the wall
;

: bottles ( -- )
    99 1 [a,b]
    [ dup 1 - 2dup [ 1 = "" "s" ? ] [email protected] verse interpolate nl ]
    each ;

SYMBOL: accumulator

CONSTANT: commands
{
    { CHAR: H [ drop "Hello, world!" print ] }
    { CHAR: Q [ print ] }
    { CHAR: 9 [ drop bottles ] }
    { CHAR: + [ drop accumulator inc ] }
    [ nip "Invalid command: %c" sprintf throw ]
}

: interpret-HQ9+ ( str -- )
    dup [ commands case ] with each accumulator off ;

: main ( -- ) command-line get first interpret-HQ9+ ;

MAIN: main


variable accumulator
: H cr ." Hello, world!" ;
: Q cr 2dup type ;
: 9 99 verses ;  \ http://rosettacode.org/wiki/99_Bottles_of_Beer#Forth
: + 1 accumulator +! ;

: hq9+ ( "code" -- )
  parse-word 2dup bounds ?do
    i 1 [ get-current literal ] search-wordlist
    if execute else true abort" invalid HQ9+ instruction"
  then loop 2drop ;


"bottle" // IF (B.NE.1) THEN "s" FI // " of beer"


' Intérprete de HQ9+
' FB 1.05.0 Win64
'

Dim Shared codigo As String: codigo = ""

Function HQ9plus(codigo As String) As String
    Dim As Byte botellas, cont
    Dim acumulador As Uinteger = 0
    Dim HQ9plus1 As String
    For cont = 1 To Len(codigo)
        Select Case Ucase(Mid(codigo, cont, 1))
        Case "H"
            HQ9plus1 = HQ9plus1 + "Hello, world!"
        Case "Q"
            HQ9plus1 = HQ9plus1 + codigo
        Case "9"
            For botellas = 99 To 1 Step -1
                HQ9plus1 = HQ9plus1 + Str(botellas) + " bottle"
                If (botellas > 1) Then HQ9plus1 = HQ9plus1 + "s"
                HQ9plus1 = HQ9plus1 + " of beer on the wall, " + Str(botellas) + " bottle"
                If (botellas > 1) Then HQ9plus1 = HQ9plus1 + "s"
                HQ9plus1 = HQ9plus1 + " of beer,"  + Chr(13) + Chr(10) +_
                "Take one down, pass it around, " + Str(botellas - 1) + " bottle"
                If (botellas > 2) Then HQ9plus1 = HQ9plus1 + "s"
                HQ9plus1 = HQ9plus1 + " of beer on the wall." + Chr(13) + Chr(10) + Chr(10)
            Next botellas
            HQ9plus1 = HQ9plus1 + "No more bottles of beer on the wall, no more bottles of beer." +_
            Chr(13) + Chr(10) + "Go to the store and buy some more, 99 bottles of beer on the wall."
        Case "+"
            acumulador = (acumulador + 1)
        Case "E"
            End
        Case Else
            'no es una instrucción válida
        End Select
        If Mid(codigo, cont, 1) <> "+" Then
            HQ9plus1 = HQ9plus1 + Chr(13) + Chr(10)
        End If
    Next cont
    HQ9plus = Left(HQ9plus1, (Len(HQ9plus1) - 2))
End Function

Cls
Do
    Input codigo
    Print HQ9plus(codigo): Print
Loop While Inkey <> Chr(27)
End


hailstone[1] = {1};
hailstone[n_] :=
  hailstone[n] = Prepend[hailstone[If[EvenQ[n], n/2, 3 n + 1]], n];
If[$ScriptCommandLine[[1]] == $Input,
  val = hailstone[27];
  Print["hailstone(27) starts with ", val[[;; 4]], ", ends with ",
   val[[-4 ;;]], ", and has length ", Length[val], "."];
  val = MaximalBy[Range[99999], [email protected]*hailstone][[1]];
  Print[val, " has the longest hailstone sequence with length ",
   Length[hailstone[val]], "."]];


def hailstone(n)
	seq = list()

	while (n > 1)
		append seq n
		if (n % 2)=0
			n = int(n / 2)
		else
			n = int((3 * n) + 1)
		end
	end
	append seq n
	return seq
end

if main
	h = hailstone(27)
	println "hailstone(27)"
	println "total elements: " + len(hailstone(27))
	print   h[0] + ", " + h[1] + ", " + h[2] + ", " + h[3] + ", ..., "
	println h[-4] + ", " + h[-3] + ", " + h[-2] + ", " + h[-1]

	max = 0
	maxLoc = 0
	for i in range(1,99999)
		result = len(hailstone(i))
		if (result > max)
			max = result
			maxLoc = i
		end
	end
	print   "\nThe number less than 100,000 with the longest sequence is "
	println maxLoc + " with a length of " + max
end


$ jar cvfe RHailstoneSequence.jar RHailstoneSequence RHailstoneSequence.class
added manifest
adding: RHailstoneSequence.class(in = 2921) (out= 1567)(deflated 46%)


proc hailstone*(n: int): auto =
  result = @[n]
  var n = n
  while n > 1:
    if (n and 1) == 1:
      n = 3 * n + 1
    else:
      n = n div 2
    result.add n

when isMainModule:
  let h = hailstone 27
  assert h.len == 112 and h[0..3] == @[27,82,41,124] and h[h.high-3..h.high] == @[8,4,2,1]
  var m, mi = 0
  for i in 1 ..< 100_000:
    let n = hailstone(i).len
    if n > m:
      m = n
      mi = i
  echo "Maximum length ", m, " was found for hailstone(", mi, ") for numbers <100,000"


#include <pari/pari.h>

#define HAILSTONE1      "n=1;print1(%d,\": \");apply(x->while(x!=1,if(x/2==x\\2,x/=2,x=x*3+1);n++;print1(x,\", \")),%d);print(\"(\",n,\")\n\")"
#define HAILSTONE2      "m=n=0;for(i=2,%d,h=1;apply(x->while(x!=1,if(x/2==x\\2,x/=2,x=x*3+1);h++),i);if(m<h,m=h;n=i));print(n,\": \",m)"

void hailstone1(int x)
{
  char buf[1024];

  snprintf(buf, sizeof(buf), HAILSTONE1, x, x);

  pari_init(1000000, 2);

  geval(strtoGENstr(buf));

  pari_close();
}

void hailstone2(int range)
{
  char buf[1024];

  snprintf(buf, sizeof(buf), HAILSTONE2, range);

  pari_init(1000000, 2);

  geval(strtoGENstr(buf));

  pari_close();
}

#if __i386__
const char _hail[] __attribute__((section(".interp"))) = "/lib/ld-linux.so.2";
#else // __x86_64__
const char _hail[] __attribute__((section(".interp"))) = "/lib64/ld-linux-x86-64.so.2";
#endif

int main(void)
{
  hailstone1(27);
  hailstone2(100000);

  exit(0);
}


Run(@ComSpec & " /c " & 'pause', "", @SW_HIDE)


BEGIN {
  system("ls")		# Unix
 #system("dir")		# DOS/MS-Windows
}


; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.

; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps

$"PRINT_LONG" = comdat any
@"PRINT_LONG" = linkonce_odr unnamed_addr constant [5 x i8] c"%ld\0A\00", comdat, align 1

;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)

;--------------------------------------------------------------------
;-- Function for calculating the nth fibonacci numbers
;--------------------------------------------------------------------
define i32 @fibonacci(i32) {
    %2 = alloca i32, align 4            ;-- allocate local copy of n
    %3 = alloca i32, align 4            ;-- allocate a
    %4 = alloca i32, align 4            ;-- allocate b
    store i32 %0, i32* %2, align 4      ;-- store copy of n
    store i32 0, i32* %3, align 4       ;-- a := 0
    store i32 1, i32* %4, align 4       ;-- b := 1
    br label %loop

loop:
    %5 = load i32, i32* %2, align 4     ;-- load n
    %6 = icmp sgt i32 %5, 0             ;-- n > 0
    br i1 %6, label %loop_body, label %exit

loop_body:
    %7 = load i32, i32* %3, align 4     ;-- load a
    %8 = load i32, i32* %4, align 4     ;-- load b
    %9 = add nsw i32 %7, %8             ;-- t = a + b
    store i32 %8, i32* %3, align 4      ;-- store a = b
    store i32 %9, i32* %4, align 4      ;-- store b = t
    %10 = load i32, i32* %2, align 4    ;-- load n
    %11 = add nsw i32 %10, -1           ;-- decrement n
    store i32 %11, i32* %2, align 4     ;-- store n
    br label %loop

exit:
    %12 = load i32, i32* %3, align 4    ;-- load a
    ret i32 %12                         ;-- return a
}

;--------------------------------------------------------------------
;-- Main function for printing successive fibonacci numbers
;--------------------------------------------------------------------
define i32 @main() {
    %1 = alloca i32, align 4            ;-- allocate index
    store i32 0, i32* %1, align 4       ;-- index := 0
    br label %loop

loop:
    %2 = load i32, i32* %1, align 4     ;-- load index
    %3 = icmp sle i32 %2, 12            ;-- index <= 12
    br i1 %3, label %loop_body, label %exit

loop_body:
    %4 = load i32, i32* %1, align 4     ;-- load index
    %5 = call i32 @fibonacci(i32 %4)
    %6 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"PRINT_LONG", i32 0, i32 0), i32 %5)
    %7 = load i32, i32* %1, align 4     ;-- load index
    %8 = add nsw i32 %7, 1              ;-- increment index
    store i32 %8, i32* %1, align 4      ;-- store index
    br label %loop

exit:
    ret i32 0                           ;-- return EXIT_SUCCESS
}


module hq9plus

function main = |args| {
  var accumulator = 0
  let source = readln("please enter your source code: ")
  foreach ch in source: chars() {
    case {
      when ch == 'h' or ch == 'H' {
        println("Hello, world!")
      }
      when ch == 'q' or ch == 'Q' {
        println(source)
      }
      when ch == '9' {
        ninety9Bottles()
      }
      when ch == '+' {
        accumulator = accumulator + 1
      }
      otherwise {
        println("syntax error")
      }
    }
  }
}

function bottles = |amount| -> match {
  when amount == 1 then "One bottle"
  when amount == 0 then "No bottles"
  otherwise amount + " bottles"
}

function ninety9Bottles = {
  foreach n in [99..0]: decrementBy(1) {
    println(bottles(n) + " of beer on the wall,")
    println(bottles(n) + " of beer!")
    println("Take one down, pass it around,")
    println(bottles(n - 1) + " of beer on the wall!")
  }
}


// live demo: http://try.haxe.org/#2E7D4
static function hq9plus(code:String):String {
	var out:String = "";
	var acc:Int = 0;
	for (position in 0 ... code.length) switch (code.charAt(position)) {
		case "H", "h": out += "Hello, World!\n";
		case "Q", "q": out += '$code\n';
		case "9":
			var quantity:Int = 99;
			while (quantity > 1) {
				out += '$quantity bottles of beer on the wall, $quantity bottles of beer.\n';
				out += 'Take one down and pass it around, ${--quantity} bottles of beer.\n';
			}
			out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
				"Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
				"No more bottles of beer on the wall, no more bottles of beer.\n" +
				"Go to the store and buy some more, 99 bottles of beer on the wall.\n";
		case "+": acc++;
	}
	return out;
}


package Hailstone;

sub seq {
	my $x = shift;
	$x == 1	? (1) : ($x & 1)? ($x, seq($x * 3 + 1))
				: ($x, seq($x / 2))
}

my %cache = (1 => 1);
sub len {
	my $x = shift;
	$cache{$x} //= 1 + (
		$x & 1	? len($x * 3 + 1)
			: len($x / 2))
}

unless (caller) {
    for (1 .. 100_000) {
        my $l = len($_);
        ($m, $len) = ($_, $l) if $l > $len;
    }
    print "seq of 27 - $cache{27} elements: @{[seq(27)]}\n";
    print "Longest sequence is for $m: $len\n";
}

1;


--global (if you want to be able to call this from test.exw)
function hailstone(atom n)
sequence s = {n}
    while n!=1 do
        if remainder(n,2)=0 then
            n /= 2
        else
            n = 3*n+1
        end if
        s &= n
    end while
    return s
end function

global function hailstone_count(atom n)
integer count = 1
    while n!=1 do
        if remainder(n,2)=0 then
            n /= 2
        else
            n = 3*n+1
        end if
        count += 1
    end while
    return count
end function

if include_file()==1 then

    sequence s = hailstone(27)
    integer ls = length(s)
    s[5..-5] = {".."}
    puts(1,"hailstone(27) = ")
    ? s
    printf(1,"length = %d\n\n",ls)

    integer hmax = 1, imax = 1,count
    for i=2 to 1e5-1 do
        count = hailstone_count(i)
        if count>hmax then
            hmax = count
            imax = i
        end if
    end for

    printf(1,"The longest hailstone sequence under 100,000 is %d with %d elements.\n",{imax,hmax})
end if


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

(de hailstone (N)
   (make
      (until (= 1 (link N))
         (setq N
            (if (bit? 1 N)
               (inc (* N 3))
               (/ N 2) ) ) ) ) )

(de hailtest ()
   (let L (hailstone 27)
      (test 112 (length L))
      (test (27 82 41 124) (head 4 L))
      (test (8 4 2 1) (tail 4 L)) )
   (let N (maxi '((N) (length (hailstone N))) (range 1 100000))
      (test 77031 N)
      (test 351 (length (hailstone N))) )
   (println 'OK)
   (bye) )


"sl"[email protected];pushes ls, = executes it, @ ends it;


include :subprocess

p subprocess.run :ls  #Lists files in directory


to fib :n [:a 0] [:b 1]
  if :n < 1 [output :a]
  output (fib :n-1 :b :a+:b)
end


procedure main(A)
repeat writes("Enter HQ9+ code: ") & HQ9(get(A)|read()|break)
end

procedure HQ9(code)
static bnw,bcr
initial {  # number matching words and line feeds for the b-th bottle
   bnw   := table(" bottles"); bnw[1] := " bottle"; bnw[0] := "No more bottles"
   bcr   := table("\n"); bcr[0]:=""
   }
every c := map(!code) do                         # ignore case
   case c of {                                   # interpret
   "h"  : write("Hello, World!")                 # . hello
   "q"  : write(code)                            # . quine
   "9"  : {                                      # . 99 bottles
          every b := 99 to 1 by -1 do writes(
             bcr[b],b,bnw[b]," of beer on the wall\n",
             b,bnw[b]," of beer\nTake one down, pass it around\n",
             1~=b|"",bnw[b-1]," of beer on the wall",bcr[b-1])
          write(", ",map(bnw[b-1])," of beer.\nGo to the store ",
                "and buy some more, 99 bottles of beer on the wall.")
          }
   "+"  : { /acc := 0 ; acc +:=1 }                # . yes it is weird
   default: stop("Syntax error in ",code)         # . error/exit
   }
return
end


#!/usr/bin/env pike

int next(int n)
{
    if (n==1)
        return 0;
    if (n%2)
        return 3*n+1;
    else
        return n/2;
}

array(int) hailstone(int n)
{
    array seq = ({ n });
    while (n=next(n))
        seq += ({ n });
    return seq;
}

void main()
{
    array(int) two = hailstone(27);
    if (equal(two[0..3], ({ 27, 82, 41, 124 })) && equal(two[<3..], ({ 8,4,2,1 })))
        write("sizeof(({ %{%d, %}, ... %{%d, %} }) == %d\n", two[0..3], two[<3..], sizeof(two));

    mapping longest = ([ "length":0, "start":0 ]);

    foreach(allocate(100000); int start; )
    {
        int length = sizeof(hailstone(start));
        if (length > longest->length)
        {
            longest->length = length;
            longest->start = start;
        }
    }
    write("longest sequence starting at %d has %d elements\n", longest->start, longest->length);
}


def hailstone(n):
    seq = [n]
    while n>1:
        n = 3*n + 1 if n & 1 else n//2
        seq.append(n)
    return seq

if __name__ == '__main__':
    h = hailstone(27)
    assert len(h)==112 and h[:4]==[27, 82, 41, 124] and h[-4:]==[8, 4, 2, 1]
    print("Maximum length %i was found for hailstone(%i) for numbers <100,000" %
          max((len(hailstone(i)), i) for i in range(1,100000)))


#include <stdlib.h>

int main()
{
    system("ls");
    return 0;
}


using System.Diagnostics;

namespace Execute
{
    class Program
    {
        static void Main(string[] args)
        {
            Process.Start("cmd.exe", "/c dir");
        }
    }
}


HAI 1.2
HOW DUZ I fibonacci YR N
  EITHER OF BOTH SAEM N AN 1 AN BOTH SAEM N AN 0
  O RLY?
    YA RLY, FOUND YR 1
    NO WAI
      I HAS A N1
      I HAS A N2
      N1 R DIFF OF N AN 1
      N2 R DIFF OF N AN 2
      N1 R fibonacci N1
      N2 R fibonacci N2
      FOUND YR SUM OF N1 AN N2
  OIC
IF U SAY SO
KTHXBYE


factorial = { x |
  true? x == 0 1 { x * factorial(x - 1)}
}


HQ9+ is a room.

After reading a command:
	interpret the player's command;
	reject the player's command.

To interpret (code - indexed text):
	let accumulator be 0;
	repeat with N running from 1 to the number of characters in code:
		let C be character number N in code in upper case;
		if C is "H":
			say "Hello, world!";
		otherwise if C is "Q":
			say "[code][line break]";
		otherwise if C is "9":
			repeat with iteration running from 1 to 99:
				let M be 100 - iteration;
				say "[M] bottle[s] of beer on the wall[line break]";
				say "[M] bottle[s] of beer[line break]";
				say "Take one down, pass it around[line break]";
				say "[M - 1] bottle[s] of beer on the wall[paragraph break]";
		otherwise if C is "+":
			increase accumulator by 1.


bob =: ": , ' bottle' , (1 = ]) }. 's of beer'"_
bobw=: bob , ' on the wall'"_
beer=: bobw , ', ' , bob , '; take one down and pass it around, ' , [email protected]<:


function hq9plus(code) {
  var out = '';
  var acc = 0;

  for (var i=0; i<code.length; i++) {
    switch (code.charAt(i)) {
      case 'H': out += "hello, world\n"; break;
      case 'Q': out += code + "\n"; break;
      case '9':
        for (var j=99; j>1; j--) {
          out += j + " bottles of beer on the wall, " + j + " bottles of beer.\n";
          out += "Take one down and pass it around, " + (j-1) + " bottles of beer.\n\n";
        }
        out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
            "Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
            "No more bottles of beer on the wall, no more bottles of beer.\n" +
            "Go to the store and buy some more, 99 bottles of beer on the wall.\n";
        break;
      case '+': acc++; break;
    }
  }
  return out;
}


#lang racket

(provide hailstone)
(define hailstone
  (let ([t (make-hasheq)])
    (hash-set! t 1 '(1))
    (λ(n) (hash-ref! t n
            (λ() (cons n (hailstone (if (even? n) (/ n 2) (+ (* 3 n) 1)))))))))

(module+ main
  (define h27 (hailstone 27))
  (printf "h(27) = ~s, ~s items\n"
          `(,@(take h27 4) ... ,@(take-right h27 4))
          (length h27))
  (define N 100000)
  (define longest
    (for/fold ([m #f]) ([i (in-range 1 (add1 N))])
      (define h (hailstone i))
      (if (and m (> (cdr m) (length h))) m (cons i (length h)))))
  (printf "for x<=~s, ~s has the longest sequence with ~s items\n"
          N (car longest) (cdr longest)))


module Hailstone {
    our sub hailstone($n) is export {
	$n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1
    }
}

sub MAIN {
    say "hailstone(27) = {.[^4]} [...] {.[*-4 .. *-1]}" given Hailstone::hailstone 27;
}


/*REXX program returns the hailstone (Collatz) sequence for any integer.*/
numeric digits 20                      /*ensure enough digits for mult. */
parse arg n 1 s                        /*N & S assigned to the first arg*/
                do  while n\==1        /*loop while  N  isn't  unity.   */
                if n//2  then n=n*3+1  /*if  N  is odd,  calc:   3*n +1 */
                         else n=n%2    /* "  "   " even, perform fast ÷ */
                s=s n                  /*build a sequence list (append).*/
                end   /*while*/
return s


# hailstone.rb
module Hailstone
  module_function
  def hailstone n
    seq = [n]
    until n == 1
      n = (n.even?) ? (n / 2) : (3 * n + 1)
      seq << n
    end
    seq
  end
end

if __FILE__ == $0
  include Hailstone

  # for n = 27, show sequence length and first and last 4 elements
  hs27 = hailstone 27
  p [hs27.length, hs27[0..3], hs27[-4..-1]]

  # find the longest sequence among n less than 100,000
  n, len = (1 ... 100_000) .collect {|n|
    [n, hailstone(n).length]} .max_by {|n, len| len}
  puts "#{n} has a hailstone sequence length of #{len}"
  puts "the largest number in that sequence is #{hailstone(n).max}"
end


(.. Runtime getRuntime (exec "cmd /C dir"))


{ spawn } = require 'child_process'

ls = spawn 'ls'

ls.stdout.on 'data', ( data ) -> console.log "Output: #{ data }"

ls.stderr.on 'data', ( data ) -> console.error "Error: #{ data }"

ls.on 'close', -> console.log "'ls' has finished executing."


(with-output-to-string (stream) (extensions:run-program "ls" nil :output stream))


integer Fibonacci(integer n) {
	if(n<2) {
		return n;
	} else {
		return Fibonacci(n-1)+Fibonacci(n-2);
	}
}
default {
	state_entry() {
		integer x = 0;
		for(x=0 ; x<35 ; x++) {
			llOwnerSay("Fibonacci("+(string)x+")="+(string)Fibonacci(x));
		}
	}
}


hello()   = println("Hello, world!")
quine()   = println(src)
bottles() = for i = 99:-1:1 print("\n$i bottles of beer on the wall\n$i bottles of beer\nTake one down, pass it around\n$(i-1) bottles of beer on the wall\n") end
acc = 0
incr()    = global acc += 1

const dispatch = Dict(
'h' => hello,
'q' => quine,
'9' => bottles,
'+' => incr)

if length(ARGS) < 1
    println("Usage: julia ./HQ9+.jl file.hq9")
    exit(1)
else
    file = ARGS[1]
end

try
    open(file) do s
        global src = readstring(s)
    end
catch
    warning("can't open $file")
    exit(1)
end

for i in lowercase(src)
    if haskey(dispatch, i) dispatch[i]() end
end


// version 1.1.3

fun hq9plus(code: String) {
    var acc = 0
    val sb = StringBuilder()
    for (c in code) {
        sb.append(
            when (c) {
                'h', 'H' -> "Hello, world!\n"
                'q', 'Q' -> code + "\n"
                '9'-> {
                    val sb2 = StringBuilder()
                    for (i in 99 downTo 1) {
                        val s = if (i > 1) "s" else ""
                        sb2.append("$i bottle$s of beer on the wall\n")
                        sb2.append("$i bottle$s of beer\n")
                        sb2.append("Take one down, pass it around\n")
                    }
                    sb2.append("No more bottles of beer on the wall!\n")
                    sb2.toString()
                 }
                '+'  -> { acc++; "" }  // yeah, it's weird!
                else -> throw IllegalArgumentException("Code contains illegal operation '$c'")
            }
        )
    }
    println(sb)
}

fun main(args: Array<String>) {
    val code = args[0]  // pass in code as command line argument (using hq9+)
    hq9plus(code)
}


object HailstoneSequence extends App { // Show it all, default number is 27.
  def hailstone(n: Int): LazyList[Int] =
    n #:: (if (n == 1) LazyList.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1))

  Hailstone.details(args.headOption.map(_.toInt).getOrElse(27))
  HailTest.main(Array())
}

object Hailstone extends App { // Compute a given or default number to Hailstone sequence
  def details(nr: Int): Unit = {
    val collatz = HailstoneSequence.hailstone(nr)

    println(s"Use the routine to show that the hailstone sequence for the number: $nr.")
    println(collatz.toList)
    println(s"It has ${collatz.length} elements.")
  }

  details(args.headOption.map(_.toInt).getOrElse(27))
}

object HailTest extends App { // Compute only the < 100000 test
  println(
    "Compute the number < 100,000, which has the longest hailstone sequence with that sequence's length.")
  val (n, len) = (1 until 100000).map(n => (n, HailstoneSequence.hailstone(n).length)).maxBy(_._2)
  println(s"Longest hailstone sequence length= $len occurring with number $n.")
}


func hailstone(n) {
    gather {
        while (n > 1) {
            take(n)
            n = (n.is_even ? n/2 : (3*n + 1))
        }
        take(1)
    }
}

if (__FILE__ == __MAIN__) {             # true when not imported
    var seq = hailstone(27)
    say "hailstone(27) - #{seq.len} elements: #{seq.ft(0, 3)} [...] #{seq.ft(-4)}"

    var n = 0
    var max = 0
    100_000.times { |i|
        var seq = hailstone(i)
        if (seq.len > max) {
            max = seq.len
            n = i
        }
    }

    say "Longest sequence is for #{n}: #{max}"
}


### In the file hailstone.tcl ###
package provide hailstone 1.0

proc hailstone n {
    while 1 {
	lappend seq $n
	if {$n == 1} {return $seq}
	set n [expr {$n & 1 ? $n*3+1 : $n/2}]
    }
}

# If directly executed, run demo code
if {[info script] eq $::argv0} {
    set h27 [hailstone 27]
    puts "h27 len=[llength $h27]"
    puts "head4 = [lrange $h27 0 3]"
    puts "tail4 = [lrange $h27 end-3 end]"

    set maxlen [set max 0]
    for {set i 1} {$i<100000} {incr i} {
	set l [llength [hailstone $i]]
	if {$l>$maxlen} {set maxlen $l;set max $i}
    }
    puts "max is $max, with length $maxlen"
}


import std.process, std.stdio;
//these two alternatives wait for the process to return, and capture the output
//each process function returns a Tuple of (int)"status" and (string)"output
auto ls_string = executeShell("ls -l"); //takes single string
writeln((ls_string.status == 0) ? ls_string.output : "command failed");

auto ls_array = execute(["ls", "-l"]); //takes array of strings
writeln((ls_array.status == 0) ? ls_array.output : "command failed");
//other alternatives exist to spawn processes in parallel and capture output via pipes


XCALL SPAWN ("ls *.jpg > file.txt")     ;execute command and continue
XCALL EXEC ("script.sh")                ;execute script or binary and exit
STOP '@/bin/ls *.jpg > file.txt'        ;exit and execute command


--calculates the nth fibonacci number. Breaks for negative or non-integer n.
function fibs(n)
  return n < 2 and n or fibs(n - 1) + fibs(n - 2)
end


int factorial(int n) {
    int result = 1;
    for (int i = 1; i <= n; ++i)
        result *= i;
    return result;
}


'Try this hq9+ program - "hq9+HqQ+Qq"
Prompt "Please input your hq9+ program."; code$
Print hq9plus$(code$)
End

Function hq9plus$(code$)
    For i = 1 to Len(code$)
        Select Case
            Case Upper$(Mid$(code$, i, 1)) = "H"
                hq9plus$ = hq9plus$ + "Hello, world!"
            Case Upper$(Mid$(code$, i, 1)) = "Q"
                hq9plus$ = hq9plus$ + code$
            Case Mid$(code$, i, 1) = "9"
                For bottles = 99 To 1 Step -1
                     hq9plus$ = hq9plus$ + str$(bottles) + " bottle"
                     If (bottles > 1) Then hq9plus$ = hq9plus$ + "s"
                     hq9plus$ = hq9plus$ + " of beer on the wall, " + str$(bottles) + " bottle"
                     If (bottles > 1) Then hq9plus$ = hq9plus$ + "s"
                     hq9plus$ = hq9plus$ + " of beer,"  + chr$(13) + chr$(10) + "Take one down, pass it around, " + str$(bottles - 1) + " bottle"
                     If (bottles > 2) Or (bottles = 1) Then hq9plus$ = hq9plus$ + "s"
                     hq9plus$ = hq9plus$ + " of beer on the wall." + chr$(13) + chr$(10)
                Next bottles
                hq9plus$ = hq9plus$ + "No more bottles of beer on the wall, no more bottles of beer." _
                                    + chr$(13) + chr$(10) + "Go to the store and buy some more, 99 bottles of beer on the wall."
            Case Mid$(code$, i, 1) = "+"
                accumulator = (accumulator + 1)
        End Select
        If Mid$(code$, i, 1) <> "+" Then
            hq9plus$ = hq9plus$ + chr$(13) + chr$(10)
        End If
    Next i
    hq9plus$ = Left$(hq9plus$, (Len(hq9plus$) - 2))
End Function


/* hailstone.wren */

var Hailstone = Fn.new { |n|
    if (n < 1) Fiber.abort("Parameter must be a positive integer.")
    var h = [n]
    while (n != 1) {
        n = (n%2 == 0) ? (n/2).floor : 3*n + 1
        h.add(n)
    }
    return h
}

var libMain_ = Fn.new {
    var h = Hailstone.call(27)
    System.print("For the Hailstone sequence starting with n = 27:")
    System.print("   Number of elements  = %(h.count)")
    System.print("   First four elements = %(h[0..3])")
    System.print("   Final four elements = %(h[-4..-1])")

    System.print("\nThe Hailstone sequence for n < 100,000 with the longest length is:")
    var longest = 0
    var longlen = 0
    for (n in 1..99999) {
        var h = Hailstone.call(n)
        var c = h.count
        if (c > longlen) {
            longest = n
            longlen = c
        }
    }
    System.print("   Longest = %(longest)")
    System.print("   Length  = %(longlen)")
}

// Check if it's being used as a library or not.
import "os" for Process
if (Process.allArguments[1] == "hailstone.wren") {  // if true, not a library
    libMain_.call()
}


fcn collatz(n,z=L()){ z.append(n); if(n==1) return(z);
   if(n.isEven) return(self.fcn(n/2,z)); return(self.fcn(n*3+1,z)) }

h27:=collatz(27);
println("Hailstone(27)-->",h27[0,4].concat(","),"...",
	h27[-4,*].concat(",")," length ",h27.len());

[2..0d100_000].pump(Void,  // loop n from 2 to 100,000
   collatz,              // generate Collatz sequence(n)
   fcn(c,n){           // if new longest sequence, save length/C, return longest
      if(c.len()>n[0]) n.clear(c.len(),c[0]); n}.fp1(L(0,0)))
.println();


program ExecuteSystemCommand;

{$APPTYPE CONSOLE}

uses Windows, ShellApi;

begin
  ShellExecute(0, nil, 'cmd.exe', ' /c dir', nil, SW_HIDE);
end.


def ls := makeCommand("ls")
ls("-l")

def [results, _, _] := ls.exec(["-l"])
when (results) -> {
  def [exitCode, out, err] := results
  print(out)
} catch problem {
  print(`failed to execute ls: $problem`)
}


function fib(x: int): int = (
   let cache = {} in
   let fibc x = if x<=1 then x else (
      if x not in cache then
      cache[x] = fibc(x-1) + fibc(x-2);
      cache[x]
   ) in fibc(x)
);;
for x in range(10) do print(fib(x))


using System;

class Program
{
    static int Factorial(int number)
    {
        if(number < 0)
            throw new ArgumentOutOfRangeException(nameof(number), number, "Must be zero or a positive number.");

        var accumulator = 1;
        for (var factor = 1; factor <= number; factor++)
        {
            accumulator *= factor;
        }
        return accumulator;
    }

    static void Main()
    {
        Console.WriteLine(Factorial(10));
    }
}


function runCode( code )
    local acc, lc = 0
    for i = 1, #code do
        lc = code:sub( i, i ):upper()
        if lc == "Q" then print( lc )
        elseif lc == "H" then print( "Hello, World!" )
        elseif lc == "+" then acc = acc + 1
        elseif lc == "9" then
            for j = 99, 1, -1 do
                if j > 1 then
                    print( string.format( "%d bottles of beer on the wall\n%d bottles of beer\nTake one down, pass it around\n%d bottles of beer on the wall\n", j, j, j - 1 ) )
                else
                    print( "1 bottle of beer on the wall\n1 bottle of beer\nTake one down and pass it around\nno more bottles of beer on the wall\n\n"..
                           "No more bottles of beer on the wall\nNo more bottles of beer\n"..
                           "Go to the store and buy some more\n99 bottles of beer on the wall.\n" )
                end
            end
        end
    end
end


hq9plus[program_] :=
 Module[{accumulator = 0, bottle},
  bottle[n_] :=
   ToString[n] <> If[n == 1, " bottle", " bottles"] <> " of beer";
  Do[Switch[chr, "H", [email protected]"hello, world", "Q", [email protected], "9",
    [email protected][
      Table[bottle[n] <> " on the wall\n" <> bottle[n] <>
        "\ntake one down, pass it around\n" <> bottle[n - 1] <>
        " on the wall" <> If[n == 1, "", "\n\n"], {n, 99, 1, -1}]],
    "+", accumulator++], {chr, [email protected]}]; accumulator]


 -- system --
-- the simplest way --
-- system spawns a new shell so I/O redirection is possible --

system( "dir /w c:\temp\ " ) -- Microsoft --

system( "/bin/ls -l /tmp" ) -- Linux BSD OSX --

----

 -- system_exec() --
 -- system_exec does not spawn a new shell --
 -- ( like bash or cmd.exe ) --

integer exit_code = 0
sequence ls_command = ""

ifdef UNIX or LINUX or OSX then
    ls_command = "/bin/ls -l "
elsifdef WINDOWS then
    ls_command = "dir /w "
end ifdef

exit_code = system_exec( ls_command )

if exit_code = -1 then
    puts( STDERR, " could not execute " & ls_command & "\n" )
elsif exit_code = 0 then
    puts( STDERR, ls_command & " succeeded\n")
else
    printf( STDERR, "command %s failed with code %d\n", ls_command, exit_code)
end if


#include <boost/iterator/counting_iterator.hpp>
#include <algorithm>

int factorial(int n)
{
  // last is one-past-end
  return std::accumulate(boost::counting_iterator<int>(1), boost::counting_iterator<int>(n+1), 1, std::multiplies<int>());
}


code = input("Enter HQ9+ program: ")

sing = function()
    for i in range(99,2)
        print i + " bottles of beer on the wall, " + i + " bottles of beer"
        print "Take one down, pass it around, " + (i-1) + " bottle" + "s"*(i>2) + " of beer on the wall"
    end for
    print "1 bottle of beer on the wall, 1 bottle of beer"
    print "Take one down, pass it around, no bottles of beer on the wall!"
end function

accumulator = 0
for c in code
    c = c.lower
    if c == "h" then print "Hello World"
    if c == "q" then print code
    if c == "9" then sing
    if c == "+" then accumulator = accumulator + 1
end for


import Nanoquery.IO

// a function to handle fatal errors
def fatal_error(errtext)
	println "%" + errtext
	println "usage: " + args[1] + " [filename.cp]"
	exit(1)
end

// a function to perform '99 bottles of beer'
def bottles(n)
	for bottles in range(n, 1, -1)
		bottlestr = ""

		if bottles = 1
			bottlestr = "bottle"
		else
			bottlestr = "bottles"
		end if

		println (bottles + " " + bottlestr + " of beer on the wall")
		println (bottles + " " + bottlestr + " of beer")
		println "Take one down, pass it around."

		if !(bottles = 2)
			println (bottles - 1 + " bottles of beer on the wall.\n")
		else
			println "1 bottle of beer on the wall.\n"
		end if
	end for
end

// get a filename from the command line and read the file in
fname = null
source = null
try
	fname = args[2]
	source = new(Nanoquery.IO.File, fname).readAll()
catch
	fatal_error("error while trying to read from specified file")
end

// define an int to be the accumulator
accum = 0

// interpreter the hq9+
for char in source
	if char = "h"
		println "hello world!"
	else if char = "q"
		println source
	else if char = "9"
		bottles(99)
	else if char = "+"
		accum += 1
	end
end


var program = "9hHqQ+"
var i = 0

proc bottle(n: int): string =
  case n
  of 0:
    result = "No more bottles"
  of 1:
    result = "1 bottle"
  else:
    result = $n & " bottles"

proc ninetyNineBottles =
  for n in countdown(99, 1):
    echo bottle(n), " bottle of beer on the wall"
    echo bottle(n), " bottle of beer"
    echo "Take one down, pass it around"
    echo bottle(n - 1), " of beer on the wall"

for token in items(program):
  case token
  of 'h', 'H':
    echo("Hello, world!")
  of 'q', 'Q':
    echo(program)
  of '9':
    ninetyNineBottles()
  of '+':
    inc(i)
  else:
    echo("Unknown command: ", token)


class Main
{
  public static Void main ()
  {
    p := Process (["ls"])
    p.run
  }
}


program SystemTest
integer :: i
 call execute_command_line ("ls", exitstat=i)
end program SystemTest


r = callJava["java.lang.Runtime", "getRuntime"]
println[read[r.exec["dir"].getInputStream[]]]


Inventory K=0:=0,1:=1
fib=Lambda K (x as decimal)-> {
      If Exist(K, x) Then =Eval(K) :Exit
      Def Ret as Decimal
      Ret=If(x>1->Lambda(x-1)+Lambda(x-2), x)
      Append K, x:=Ret
      =Ret
}
\\ maximum 139
For i=1 to 139 {
      Print Fib(i)
}


fn int factorial(int n)
{
    int result = 1;
    for (int i = 1; i <= n; ++i)
    {
        result *= i;
    }
    return result;
}


define rec_fac
      { dup 1 <= [pop 1] [dec rec_fac *] if }


10 INPUT "INPUT HQ9+ CODE: ",I$
20 B$="S"
30 W$=" ON THE WALL"
40 FOR I=1 TO LEN(I$)
50 C$=MID$(I$,I,1)
60 IF C$="H" THEN PRINT "HELLO, WORLD!"
70 IF C$="Q" THEN PRINT I$
80 A=A+(C$="+")
90 IF C$<>"9" GOTO 200
100 FOR B=99 TO 1 STEP -1
110 IF B=1 THEN B$=""
120 PRINT B " BOTTLE"B$" OF BEER" W$
130 PRINT B " BOTTLE"B$" OF BEER"
140 PRINT "TAKE ONE DOWN,"
150 PRINT "PASS IT AROUND"
160 IF B=2 THEN B$=""
170 IF B=1 THEN B$="S"
180 PRINT B-1 " BOTTLE"B$" OF BEER" W$
190 NEXT
200 NEXT


let hq9p line =
  let accumulator = ref 0 in
  for i = 0 to (String.length line - 1) do
    match line.[i] with
    | 'h' | 'H' -> print_endline "Hello, world!"
    | 'q' | 'Q' -> print_endline line
    | '9' -> beer 99
    | '+' -> incr accumulator
  done


beer(n)={
  if(n == 1,
    print("1 bottle of beer on the wall");
    print("1 bottle of beer");
    print("Take one down and pass it around");
    print("No bottles of beer on the wall")
  ,
    print(n" bottles of beer on the wall");
    print(n" bottles of beer");
    print("Take one down and pass it around");
    print(n-1," bottles of beer on the wall\n");
    beer(n-1)
  )
};
HQ9p(s)={
  my(accum=0,v=Vec(s));
  for(i=1,#s,
    if(v[i] == "H" || v[i] == "h", print("Hello, world!"); next);
    if(v[i] == "Q" || v[i] == "q", print(s); next);
    if(v[i] == "9", beer(99); next);
    if(v[i] == "+", accum++, error("Nasal demons"))
  )
};


import sys.execute

execute( if $os.startsWith('Windows') then 'dir' else 'ls' )


include "ConsoleWindow"

local fn DoUnixCommand( cmd as str255 )
  dim as str255 s

  open "Unix", 2, cmd
  while ( not eof(2) )
    line input #2, s
    print s
  wend
  close 2
end fn

fn DoUnixCommand( "ls -A" )


[indent=4]
/*
  Execute system command, in Genie

  valac executeSystemCommand.gs
  ./executeSystemCommand
*/

init
    try
        // Non Blocking
        Process.spawn_command_line_async("ls")
    except e : SpawnError
        stderr.printf("%s\n", e.message)


shared void run() {

	Integer? recursiveFactorial(Integer n) =>
			switch(n <=> 0)
			case(smaller) null
			case(equal) 1
			case(larger) if(exists f = recursiveFactorial(n - 1)) then n * f else null;

	Integer? iterativeFactorial(Integer n) =>
			switch(n <=> 0)
			case(smaller) null
			case(equal) 1
			case(larger) (1:n).reduce(times);

	for(Integer i in 0..10) {
		print("the iterative factorial of     ``i`` is ``iterativeFactorial(i) else "negative"``
		       and the recursive factorial of ``i`` is ``recursiveFactorial(i) else "negative"``\n");
	}
}


proc fac(n) {
	var r = 1;
	for i in 1..n do
		r *= i;

	return r;
}


program HQ9;

procedure runCode(code: string);
var
  c_len, i, bottles: Integer;
  accumulator: Cardinal;
begin
  c_len := Length(code);
  accumulator := 0;
  for i := 1 to c_len do
  begin
    case code[i] of
      'Q','q':
        writeln(code);
      'H','h':
        Writeln('Hello, world!');
      '9':
        begin
          bottles := 99;
          repeat
            writeln(bottles,' bottles of beer on the wall');
            writeln(bottles,' bottles of beer');
            Writeln('Take one down, pass it around');
            dec(bottles);
            writeln(bottles,' bottles of beer on the wall',#13#10);
          until (bottles <= 0);
        end;
      '+':
        inc(accumulator);
    end;
  end;
end;
BEGIN
  runCode('QqQh');
  //runCode('HQ9+');// output to long
END.


#!/usr/bin/perl
use warnings;
use strict;
use feature qw(say switch);

my @programme = <> or die "No input. Specify a program file or pipe it to the standard input.\n";

for (@programme) {
    for my $char (split //) {
        given ($char) {
            when ('H') { hello()             }
            when ('Q') { quinne(@programme)  }
            when ('9') { bottles()           }
            default    { die "Unknown instruction $char.\n" } # Comment this line to ignore other instructions.
        }
    }
}

sub hello {
    print 'Hello World';
}

sub quinne {
    print @programme;
}

sub bottles {
    for my $n (reverse 0 .. 99) {
        my $before = bottle_count($n);
        my $after  = bottle_count($n - 1);
        my $action = bottle_action($n);
        say "\u$before of beer on the wall, $before of beer.";
        say "$action, $after of beer on the wall.";
        say q() if $n;
    }
}

sub bottle_count {
    my $n = shift;
    given ($n) {
        when    (-1) { return '99 bottles'      }
        when    (0)  { return 'no more bottles' }
        when    (1)  { return '1 bottle'        }
        default      { return "$n bottles"      }
    }
}

sub bottle_action {
    my $n = shift;
    return 'Take one down and pass it around' if $n > 0;
    return 'Go to the store and buy some more';
}


package main

import (
    "log"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls", "-l")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    if err := cmd.Run(); err != nil {
        log.Fatal(err)
    }
}


SYSTEM(CoMmand='pause')
SYSTEM(CoMmand='dir & pause')


            NORMAL MODE IS INTEGER

            INTERNAL FUNCTION(N)
            ENTRY TO FIB.
            A = 0
            B = 1
            THROUGH LOOP, FOR N=N, -1, N.E.0
            C = A + B
            A = B
LOOP        B = C
            FUNCTION RETURN A
            END OF FUNCTION

            THROUGH SHOW, FOR I=0, 1, I.GE.20
SHOW        PRINT FORMAT FNUM, I, FIB.(I)
            VECTOR VALUES FNUM = $4HFIB(,I2,4H) = ,I4*$
            END OF PROGRAM


Caramel Factorials.

Only reads one value.

Ingredients.
1 g Caramel
2 g Factorials

Method.
Take Factorials from refrigerator.
Put Caramel into 1st mixing bowl.
Verb the Factorials.
Combine Factorials into 1st mixing bowl.
Verb Factorials until verbed.
Pour contents of the 1st mixing bowl into the 1st baking dish.

Serves 1.


with javascript_semantics
-- copied from 99_Bottles_of_Beer
constant ninetynine = 2 -- (set this to 9 for testing)

function bottles(integer count)
    if count=0 then     return "no more bottles"
    elsif count=1 then  return "1 bottle" end if
    if count=-1 then count = ninetynine end if
    return sprintf("%d bottles",count)
end function

function bob(integer count)
    return bottles(count)&" of beer"
end function

function up1(string bob)
-- Capitalise sentence start (needed just the once, "no more"=>"No more")
    bob[1] = upper(bob[1])
    return bob
end function

procedure ninetyninebottles()
    string thus = bob(ninetynine),
           that = "Take one down, pass it around,\n"
    for i=ninetynine to 0 by -1 do
        puts(1,up1(thus)&" on the wall,\n")
        puts(1,thus&".\n")
        if i=0 then that = "Go to the store, buy some more,\n"
        elsif i=1 then that[6..8] = "it" end if
        thus = bob(i-1)
        puts(1,that&thus&" on the wall.\n\n")
    end for
--  if getc(0) then end if
end procedure

-- the interpreter

procedure hq9(string code)
    integer accumulator = 0
    for i=1 to length(code) do
        switch(upper(code[i]))
            case 'H': printf(1,"Hello, world!\n")
            case 'Q': printf(1,"%s\n", code);
            case '9': ninetyninebottles()
            case '+': accumulator += 1
        end switch
    end for
end procedure

hq9("h9+HqQ+Qq")


procedure main()

write("Trying command ",cmd := if &features == "UNIX" then "ls" else "dir")
system(cmd)

end


0 => int total;
fun int factorial(int i)
{
    if (i == 0) return 1;
    else
    {
        i * factorial(i - 1) => total;
    }
    return total;
}

// == another way
fun int factorial(int x)
{
    if (x <= 1 ) return 1;
    else return x * factorial (x - 1);
}

// call
factorial (5) => int answer;

// test
if ( answer == 120 ) <<<"success">>>;


/*
H 	Prints "Hello, world!"
Q 	Prints the entire text of the source code file.
9 	Prints the complete canonical lyrics to "99 Bottles of Beer on the Wall"
+ 	Increments the accumulator.
 */
$accumulator = 0;
echo 'HQ9+: ';
$program = trim(fgets(STDIN));

foreach (str_split($program) as $chr) {
    switch ($chr) {
        case 'H':
        case 'h':
            printHelloWorld();
            break;
        case 'Q':
        case 'q':
            printSource($program);
            break;
        case '9':
            print99Bottles();
            break;
        case '+':
            $accumulator = incrementAccumulator($accumulator);
            break;
        default:
            printError($chr);
    }
}

function printHelloWorld() {
    echo 'Hello, world!'. PHP_EOL;
}

function printSource($program) {
    echo var_export($program, true) . PHP_EOL;
}

function print99Bottles() {
    $n = 99;
    while($n >= 1) {
        echo $n;
        echo ' Bottles of Beer on the Wall ';
        echo $n;
        echo ' bottles of beer, take one down pass it around ';
        echo $n-1;
        echo ' bottles of beer on the wall.'. PHP_EOL;
        $n--;
    }
}

function incrementAccumulator($accumulator) {
    return ++$accumulator;
}

function printError($chr) {
    echo "Invalid input: ". $chr;
}


(de hq9+ (Code)
   (let Accu 0
      (for C (chop Code)
         (case C
            ("H" (prinl "Hello, world"))
            ("Q" (prinl Code))
            ("9"
               (for (N 99 (gt0 N))
                  (prinl N " bottles of beer on the wall")
                  (prinl N " bottles of beer")
                  (prinl "Take one down, pass it around")
                  (prinl (dec 'N) " bottles of beer on the wall")
                  (prinl) ) )
            ("+" (inc 'Accu)) ) )
      Accu ) )


load'task'

NB.  Execute a command and wait for it to complete
shell 'dir'

NB.  Execute a command but don't wait for it to complete
fork 'notepad'

NB.  Execute a command and capture its stdout
stdout   =:  shell 'dir'

NB.  Execute a command, provide it with stdin,
NB.  and capture its stdout
stdin    =:  'blahblahblah'
stdout   =:  stdin spawn 'grep blah'


import java.util.Scanner;
import java.io.*;

public class Program {
    public static void main(String[] args) {
    	try {
    		Process p = Runtime.getRuntime().exec("cmd /C dir");//Windows command, use "ls -oa" for UNIX
    		Scanner sc = new Scanner(p.getInputStream());
    		while (sc.hasNext()) System.out.println(sc.nextLine());
    	}
    	catch (IOException e) {
    		System.out.println(e.getMessage());
    	}
    }
}


var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause");


fib[0] = 0
fib[1] = 1
fib[n_Integer] := fib[n - 1] + fib[n - 2]


factorialRec(n) {
    if (n == 0) return 1;
    return n * factorialRec(n - 1);
}

factorialIter(n) {
    for (i in range(1, n))
        n *= i;
    return n;
}

factorialFold(n) {
    return reduce(multiply, 1, range(1, n + 1));
}


fn factorial n:
  if n <= 1: n
  else:
    n * (n - 1 -> factorial)

10 -> factorial -> print


function Invoke-HQ9PlusInterpreter ([switch]$Global)
{
    $sb = New-Object -TypeName System.Text.StringBuilder

    for ($i = 99; $i -gt 2; $i--)
    {
        $sb.Append((("{0,2} bottles of beer on the wall, " +
                     "{0,2} bottles of beer! Take one down, pass it around, " +
                     "{1,2} bottles of beer on the wall.`n") -f $i, ($i - 1))) | Out-Null
    }
    $sb.Append((" 2 bottles of beer on the wall, " +
                " 2 bottles of beer! Take one down, pass it around, " +
                " 1 bottle  of beer on the wall.`n")) | Out-Null
    $sb.Append((" 1 bottle  of beer on the wall, " +
                " 1 bottle  of beer! Take one down, pass it around...`n")) | Out-Null
    $sb.Append(("No more bottles of beer on the wall, No more bottles of beer!`n" +
                "Go to the store and get us some more, 99 bottles of beer on the wall!")) | Out-Null

    $99BottlesOfBeer = $sb.ToString()

    $helloWorld = "Hello, world!"

    if ($Global) {New-Variable -Name "+" -Value 0 -Scope Global -ErrorAction SilentlyContinue}

    Write-Host "Press Ctrl-C or Enter nothing to exit." -ForegroundColor Cyan

    while ($code -ne "")
    {
        $code = Read-Host -Prompt "HQ9+"

        ($code.ToCharArray() | Select-String -Pattern "[HQ9+]").Matches.Value | ForEach-Object {
            switch ($_)
            {
                "H" {$helloWorld;           break}
                "Q" {$code;                 break}
                "9" {$99BottlesOfBeer;      break}
                "+" {if ($Global) {${global:+}++}}
            }
        }
    }
}

Set-Alias -Name HQ9+ -Value Invoke-HQ9PlusInterpreter


Procedure hq9plus(code.s)
  Protected accumulator, i, bottles
  For i = 1 To Len(code)
    Select Mid(code, i, 1)
      Case "h", "H"
        PrintN("Hello, world!")
      Case "q", "Q"
        PrintN(code)
      Case "9"
        bottles = 99
        While bottles
          PrintN(Str(bottles) + " bottles of beer on the wall, " + Str(bottles) + " bottles of beer,")
          bottles - 1
          PrintN("Take one down, pass it around, " + Str(bottles) + " bottles of beer on the wall.")
        Wend
      Case "+"
        accumulator + 1
    EndSelect
  Next i
EndProcedure

If OpenConsole()
  Define testCode.s = "hq9+HqQ+Qq"
  hq9plus(testCode)

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


// version 1.0.6

import java.util.Scanner

fun main(args: Array<String>) {
    val proc = Runtime.getRuntime().exec("cmd /C dir")  // testing on Windows 10
    Scanner(proc.inputStream).use {
        while (it.hasNextLine()) println(it.nextLine())
    }
}


local(
	path	= file_forceroot,
	ls	= sys_process('/bin/ls', (:'-l', #path)),
	lswait	= #ls -> wait
)
'<pre>'
#ls -> read
'</pre>'


 (deffunction factorial (?a)
    (if (or (not (integerp ?a)) (< ?a 0)) then
        (printout t "Factorial Error!" crlf)
     else
        (if (= ?a 0) then
            1
         else
            (* ?a (factorial (- ?a 1))))))


$ "bottles.qky" loadfile ( if required, the source code for this can be found at
                           http://rosettacode.org/wiki/99_bottles_of_beer#Quackery )

[ stack ]                  is accumulator (   --> s )

[ stack ]                  is sourcecode  (   --> s )

[ say "Hello, world!" cr ] is H.HQ9+      (   -->   )

[ sourcecode share
  echo$ cr ]               is Q.HQ9+      (   -->   )

[ 99 song echo$ ]          is 9.HQ9+      (   -->   )

[ 1 accumulator tally ]    is +.HQ9+      (   -->   )

[ dup sourcecode put
  0 accumulator put
  witheach
    [ $ ".HQ9+" join
      quackery ]
  sourcecode release
  cr say "Accumulator = "
  accumulator take echo ]  is HQ9+        ( $ -->   )

$ "HH+QQQQ+" HQ9+


#lang racket
; if we `for` over the port, we won't have the program in memory for 'Q'
(define (parse-HQ9+ the-program)
  (define oTW " on the wall")
  (and ; ensures the accumulator is never seen!
   (for/fold ((A 0))
     ((token (in-string the-program)))
     (case token
       ((#\H) (display "hello, world") A)
       ((#\Q) (display the-program) A)
       ;; official esolang version of 99-BoB at:
       ;;  http://esolangs.org/wiki/99_bottles_of_beer
       ((#\9)
        (displayln
        (let ((BoB (lambda (n)
                     (string-append
                      (case n ((1) "1 bottle") ((0) "No bottles")
                        (else (format "~a bottles" n)))
                      " of beer"))))
          (string-join
           (for/list ((btls (in-range 99 0 -1)))
            (string-append (BoB btls)oTW",\n"(BoB btls)
                           ".\nTake one down, pass it around,\n"
                           (BoB (sub1 btls))oTW"."))
           "\n\n"))) A)
       ((#\+) (add1 A))
       ((#\newline) ; language extension, makes getting standard in easier
        (eprintf "warning: HQ9+: language extension ~s" token)
        A)
       (else (error "syntax error: HQ9+: unrecognised token ~s" token))))
   (void)))

(module+ main (parse-HQ9+ (port->string)))

(module+ test
  (require rackunit)
  (check-equal? (with-output-to-string (lambda () (parse-HQ9+ ""))) "")
  (check-equal? (with-output-to-string (lambda () (parse-HQ9+ "H"))) "hello, world")
  (check-equal? (with-output-to-string (lambda () (parse-HQ9+ "Q"))) "Q")
  (check-equal? (with-output-to-string (lambda () (parse-HQ9+ "QQ"))) "QQQQ")
  (check-equal? (with-output-to-string (lambda () (parse-HQ9+ "+"))) "")
  (check-equal? (with-output-to-string (lambda () (parse-HQ9+ "+"))) "")
  (check-equal? (with-output-to-string (lambda () (parse-HQ9+ "++"))) "")
  (check-equal? (with-output-to-string (lambda () (parse-HQ9+ "+++"))) "")
  (check-equal? (with-output-to-string (lambda () (parse-HQ9+ "+++++++++++++++++"))) "")
  (check-equal? (with-output-to-string (lambda () (parse-HQ9+ (make-string 10000 #\+)))) "")
  ;;; you can jolly well read (and sing along to) the output of '9'
  )


class HQ9Interpreter {
    has @!code;
    has $!accumulator;
    has $!pointer;

    method run ($code) {
        @!code = $code.comb;
        $!accumulator = 0;
        $!pointer = 0;
        while $!pointer < @!code {
            given @!code[$!pointer].lc {
                when 'h' { say 'Hello world!' }
                when 'q' { say @!code }
                when '9' { bob(99) }
                when '+' { $!accumulator++ }
                default  { note "Syntax error: Unknown command \"{@!code[$!pointer]}\"" }
            }
	    $!pointer++;
        }
    }
    sub bob ($beer is copy) {
        sub what  { "{$beer??$beer!!'No more'} bottle{$beer-1??'s'!!''} of beer" };
        sub where { 'on the wall' };
        sub drink { $beer--; "Take one down, pass it around," }
        while $beer {
            .say for "&what() &where(),", "&what()!",
                     "&drink()", "&what() &where()!", ''
        }
    }
}

# Feed it a command string:

my $hq9 = HQ9Interpreter.new;
$hq9.run("hHq+++Qq");
say '';
$hq9.run("Jhq.k+hQ");


 drive1$ = left$(Drives$,1)
run "cmd.exe /";drive1$;" dir & pause"


implement Runls;

include "sys.m"; sys: Sys;
include "draw.m";
include "sh.m";

Runls: module {
	init: fn(ctxt: ref Draw->Context, args: list of string);
};

init(ctxt: ref Draw->Context, args: list of string)
{
	sys = load Sys Sys->PATH;
	ls := load Command "/dis/ls.dis";
	if(ls == nil)
		die("Couldn't load /dis/ls.dis");
	ls->init(ctxt, "ls" :: tl args);
}

die(s: string)
{
	sys->fprint(sys->fildes(2), "runls: %s: %r", s);
	raise "fail:errors";
}


sx = xtra("Shell").new()
if the platform contains "win" then
  put sx.shell_cmd("dir")
else
  put sx.shell_cmd("ls")
end if


print first butfirst shell [ls -a]   ; ..


(defn factorial [x]
  (apply * (range 2 (inc x))))


/*REXX program implements the   HQ9+   language. ───────────────────────────────────────*/
arg pgm .                                                    /*obtain optional argument.*/
accumulator=0                                                /*assign default to accum. */

      do instructions=1  for length(pgm);               ?=substr(pgm, instructions, 1)
           select
           when ?=='H' then say "Hello, world!"              /*text varies on definition*/
           when ?=='Q' then do j=1  for sourceline();   say sourceline(j);   end  /*j*/
           when ?== 9  then call 99
           when ?=='+' then accumulator=accumulator+1
           otherwise say 'invalid HQ9+ instruction:' ?
           end   /*select*/
      end        /*instructions*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
99:           do j=99  by -1  to 1
              say j 'bottle's(j)  "of beer the wall,"
              say j 'bottle's(j)  "of beer."
              say 'Take one down, pass it around,'
              n=j-1
              if n==0 then n='no'                                 /*cheating to use  0. */
              say n  'bottle's(j-1)  "of beer the wall."
              say
              end   /*j*/
    say 'No more bottles of beer on the wall,'                    /*finally, last verse.*/
    say 'no more bottles of beer.'
    say 'Go to the store and buy some more,'
    say '99 bottles of beer on the wall.'
    return
/*──────────────────────────────────────────────────────────────────────────────────────*/
s:  if arg(1)==1  then return '';             return "s"          /*a simple pluralizer.*/


# Project : Execute HQ9

bottle("hq9+HqQ+Qq")

func bottle(code)
     accumulator = 0
     for i = 1 to len(code)
         switch code[i]
                on "h"
                    see "Hello, world!" + nl
                on "H"
                    see "hello, world!" + nl
                on "q"
                    see code + nl
                on "Q"
                    see code + nl
                on "9"
                    bottles = 99
                    while bottles > 0
                          see "" + bottles + " bottles of beer on the wall, "
                          see "" + bottles + " bottles of beer," + nl
                          bottles = bottles - 1
                          see "take one down, pass it around, "
                          see "" + bottles + " bottles of beer on the wall." + nl
                    end
                on "+"
                    accumulator = accumulator + 1
         off
     next


-- just executing the command
os.execute("ls")

-- to execute and capture the output, use io.popen
local f = io.popen("ls") -- store the output in a "file"
print( f:read("*a") )    -- print out the "file"'s content


fn fibIter n =
(
    if n < 2 then
    (
        n
    )
    else
    (
        fib = 1
        fibPrev = 1
        for num in 3 to n do
        (
            temp = fib
            fib += fibPrev
            fibPrev = temp
        )
        fib
    )
)


factorial = proc (n: int) returns (int) signals (negative)
    if n<0 then signal negative
    elseif n=0 then return(1)
    else return(n * factorial(n-1))
    end
end factorial

start_up = proc ()
    po: stream := stream$primary_output()

    for i: int in int$from_to(0, 10) do
        fac: int := factorial(i)
        stream$putl(po, int$unparse(i) || "! = " || int$unparse(fac))
    end
end start_up


function(factorial var n)
  set(product 1)
  foreach(i RANGE 2 ${n})
    math(EXPR product "${product} * ${i}")
  endforeach(i)
  set(${var} ${product} PARENT_SCOPE)
endfunction(factorial)

factorial(f 12)
message("12! = ${f}")


use std::env;

// HQ9+ requires that '+' increments an accumulator, but it's inaccessible (and thus, unused).
#[allow(unused_variables)]
fn execute(code: &str) {
    let mut accumulator = 0;

    for c in code.chars() {
        match c {
            'Q' => println!("{}", code),
            'H' => println!("Hello, World!"),
            '9' => {
                for n in (1..100).rev() {
                    println!("{} bottles of beer on the wall", n);
                    println!("{} bottles of beer", n);
                    println!("Take one down, pass it around");
                    if (n - 1) > 1 {
                        println!("{} bottles of beer on the wall\n", n - 1);
                    } else {
                        println!("1 bottle of beer on the wall\n");
                    }
                }
            }
            '+' => accumulator += 1,
            _ => panic!("Invalid character '{}' found in source.", c),
        }
    }
}

fn main() {
    execute(&env::args().nth(1).unwrap());
}


def hq9plus(code: String) : String = {
    var out = ""
    var acc = 0

    def bottle(num: Int) : Unit = {
        if (num > 1) {
            out += num + " bottles of beer on the wall, " + num + " bottles of beer.\n"
            out += "Take one down and pass it around, " + (num - 1) + " bottle"

            if (num > 2) out += "s"

            out += " of beer.\n\n"
            bottle(num - 1)
        }
        else {
            out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
                "Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
                "No more bottles of beer on the wall, no more bottles of beer.\n" +
                "Go to the store and buy some more, 99 bottles of beer on the wall.\n"
        }
    }

    def handle(char: Char) = char match {
        case 'H' => out += "Hello world!\n"
        case 'Q' => out += code + "\n"
        case '+' => acc += 1
        case '9' => bottle(99)
    }

    code.toList foreach handle
    out
}

println(hq9plus("HQ9+"))


>> system('PAUSE')

Press any key to continue . . .

ans =

     0


:- module execute_sys_cmd.
:- interface.
:- import_module io.

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

:- implementation.

main(!IO) :-
   io.call_system("ls", _Result, !IO).


MODULE tri;

FROM   SYSTEM           IMPORT  ADR;
FROM   SysLib           IMPORT  system;

IMPORT TextIO, InOut, ASCII;

VAR   fd                : TextIO.File;
      ch                : CHAR;

PROCEDURE SystemCommand (VAR  command : ARRAY OF CHAR) : BOOLEAN;

BEGIN
   IF  system (ADR (command) ) = 0  THEN
      RETURN TRUE
   ELSE
      RETURN FALSE
   END
END SystemCommand;

BEGIN
   IF  SystemCommand ("ls -1 tri.mod | ") = TRUE  THEN
      InOut.WriteString ("No error reported.")
   ELSE
      InOut.WriteString ("Error reported!")
   END;
   LOOP
      InOut.Read (ch);
      InOut.Write (ch);
      IF  ch < ' '  THEN  EXIT  END
   END;
   InOut.WriteLn;
   InOut.WriteBf
END tri.


% The following code is derived from the Mercury Tutorial by Ralph Becket.
% http://www.mercury.csse.unimelb.edu.au/information/papers/book.pdf
:- module fib.

:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module int.

:- pred fib(int::in, int::out) is det.
fib(N, X) :-
    ( if N =< 2
          then X = 1
          else fib(N - 1, A), fib(N - 2, B), X = A + B ).

:- func fib(int) = int is det.
fib(N) = X :- fib(N, X).

main(!IO) :-
    fib(40, X),
    write_string("fib(40, ", !IO),
    write_int(X, !IO),
    write_string(")\n", !IO),

    write_string("fib(40) = ", !IO),
    write_int(fib(40), !IO),
    write_string("\n", !IO).


T U0 {}
T U1 {}

F baz(i)
   I i == 0
      X U0()
   E
      X U1()

F bar(i)
   baz(i)

F foo()
   L(i) 0..1
      X.try
         bar(i)
      X.catch U0
         print(‘Function foo caught exception U0’)

foo()


fac = (n) ->
  if n <= 1
    1
  else
    n * fac n-1


$ include "seed7_05.s7i";

const proc: runCode (in string: code) is func
  local
    var char: ch is ' ';
    var integer: bottles is 0;
    var integer: accumulator is 0;
  begin
    for ch range code do
      case ch of
        when {'H'}: writeln("Hello, world!");
        when {'Q'}: writeln(code);
        when {'9'}: bottles := 99;
                    repeat
                      writeln(bottles <& " bottles of beer on the wall");
                      writeln(bottles <& " bottles of beer");
                      writeln("Take one down, pass it around");
                      decr(bottles);
                      writeln(bottles <& " bottles of beer on the wall");
                      writeln;
                    until bottles = 0;
        when {'+'}: incr(accumulator);
      end case;
    end for;
  end func;

const proc: main is func
  begin
    if length(argv(PROGRAM)) >= 1 then
      runCode(argv(PROGRAM)[1]);
    end if;
  end func;


class HQ9Interpreter {
    has pointer;
    has accumulator;

    func bob (beer) {
        func what  { "#{beer ? beer : 'No more'} bottle#{beer-1 ? 's' : ''} of beer" }
        func where { 'on the wall' }
        func drink { beer--; "Take one down, pass it around," }

        while (beer.is_pos) {
            [[what(), where()], [what()],
            [drink()], [what(), where()], []].each{.join(' ').say}
        }
    }

    method run (code) {
        var chars = code.chars;
        accumulator = 0;
        pointer = 0;
        while (pointer < chars.len) {
            given (chars[pointer].lc) {
                when ('h') { say 'Hello world!' }
                when ('q') { say code }
                when ('9') { bob(99) }
                when ('+') { accumulator++ }
                default    { warn %Q(Syntax error: Unknown command "#{chars[pointer]}") }
            }
            pointer++;
        }
    }
}


UNSAFE MODULE Exec EXPORTS Main;

IMPORT Unix, M3toC;

VAR command := M3toC.CopyTtoS("ls");

BEGIN
  EVAL Unix.system(command);
  M3toC.FreeCopiedS(command);
END Exec.


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

import java.util.Scanner

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  parse arg command
  if command = '' then command = 'ls -oa' -- for Windows change to: 'cmd /C dir'
  do
    say 'Executing command:' command
    jprocess = Runtime.getRunTime().exec(command)
    jscanner = Scanner(jprocess.getInputStream())
    loop label scanning while jscanner.hasNext()
      say jscanner.nextLine()
      end scanning
  catch ex = IOException
    ex.printStackTrace()
  end
  return


vardef fibo(expr n) =
if n=0: 0
elseif n=1: 1
else:
  fibo(n-1) + fibo(n-2)
fi
enddef;

for i=0 upto 10: show fibo(i); endfor
end


with Ada.Text_Io; use Ada.Text_Io;

procedure Exceptions_From_Nested_Calls is
   U0 : exception;
   U1 : exception;
   Baz_Count : Natural := 0;
   procedure Baz is
   begin
      Baz_Count := Baz_Count + 1;
      if Baz_Count = 1 then
         raise U0;
      else
         raise U1;
      end if;
   end Baz;
   procedure Bar is
   begin
      Baz;
   end Bar;
   procedure Foo is
   begin
      Bar;
   exception
      when U0 =>
         Put_Line("Procedure Foo caught exception U0");
   end Foo;
begin
   for I in 1..2 loop
      Foo;
   end loop;
end Exceptions_From_Nested_Calls;


void
baz(integer i)
{
    error(cat("U", itoa(i)));
}

void
bar(integer i)
{
    baz(i);
}

void
foo(void)
{
    integer i;

    i = 0;
    while (i < 2) {
        text e;

        if (trap_d(e, bar, i)) {
            o_form("Exception `~' thrown\n", e);
            if (e != "U0") {
		o_text("will not catch exception\n");
		error(e);
	    }
	}
	i += 1;
    }

    o_text("Never reached.\n");
}

integer
main(void)
{
    foo();

    return 0;
}


MODE OBJ = STRUCT(
  INT value,
  STRUCT(
    STRING message,
    FLEX[0]STRING args,
    PROC(REF OBJ)BOOL u0, u1
  ) exception
);

PROC on u0 = (REF OBJ self, PROC (REF OBJ) BOOL mended)VOID:
  u0 OF exception OF self := mended;

PROC on u1 = (REF OBJ self, PROC (REF OBJ) BOOL mended)VOID:
  u1 OF exception OF self := mended;

PRIO INIT = 1, RAISE = 1;

OP INIT = (REF OBJ self, INT value)REF OBJ: (
  value OF self := value;
  u0 OF exception OF self := u1 OF exception OF self := (REF OBJ skip)BOOL: FALSE;
  args OF exception OF self := message OF exception OF self := "OBJ Exception";
  self
);

OP RAISE = (REF OBJ self, PROC (REF OBJ) BOOL mended)VOID:
  IF NOT mended(self) THEN
    put(stand error, (message OF exception OF self+" not caught - stop", new line));
    stop
  FI;

PROC (REF OBJ)VOID bar, baz; # early declaration is required by the ALGOL 68RS subset language #

PROC foo := VOID:(
    FOR value FROM 0 TO 1 DO
        REF OBJ i = LOC OBJ INIT value;
        on u0(i, (REF OBJ skip)BOOL: (GO TO except u0; SKIP ));
            bar(i);
        GO TO end on u0;
        except u0:
            print(("Function foo caught exception u0", new line));
        end on u0: SKIP
    OD
);

# PROC # bar := (REF OBJ i)VOID:(
    baz(i) # Nest those calls #
);

# PROC # baz := (REF OBJ i)VOID:
    IF value OF i = 0 THEN
        i RAISE u0 OF exception OF i
    ELSE
        i RAISE u1 OF exception OF i
    FI;

foo


  PROC Recursive(n) CLOSED
    r:=1
    IF n>1 THEN
      r:=n*Recursive(n-1)
    ENDIF
    RETURN r
  ENDPROC Recursive


n = 5 # calculates n!
acc = 1

factorial
  comefrom

  comefrom accumulate if n < 1

accumulate
  comefrom factorial
  acc = acc * n
  comefrom factorial if n is 0
  n = n - 1

acc # prints the result


import "os" for Process

var hq9plus = Fn.new { |code|
    var acc = 0
    var sb = ""
    for (c in code) {
        if (c == "h" || c == "H") {
            sb = sb + "Hello, world!\n"
        } else if (c == "q" || c == "Q") {
            sb = sb + code + "\n"
        } else if (c == "9") {
            for (i in 99..1) {
                var s = (i > 1) ? "s" : ""
                sb = sb + "%(i) bottle%(s) of beer on the wall\n"
                sb = sb + "%(i) bottle%(s) of beer\n"
                sb = sb + "Take one down, pass it around\n"
            }
            sb = sb + "No more bottles of beer on the wall!\n"
        } else if (c == "+") {
            acc = acc + 1
        } else {
            Fiber.abort("Code contains illegal operation '%(c)'")
        }
    }
    System.print(sb)
}

var args = Process.arguments
if (args.count != 1) {
    System.print("Please pass in the HQ9+ code to be executed.")
} else {
    hq9plus.call(args[0])
}


import osproc

let exitCode = execCmd "ls"
let (output, exitCode2) = execCmdEx "ls"


void runls()
{
    [[NSTask launchedTaskWithLaunchPath:@"/bin/ls"
        arguments:@[]] waitUntilExit];
}


' Fibonacci sequence - 31/07/2018
  n = 139
  f1 = 0
  f2 = 1
  TextWindow.WriteLine("fibo(0)="+f1)
  TextWindow.WriteLine("fibo(1)="+f2)
  For i = 2 To n
    f3 = f1 + f2
    TextWindow.WriteLine("fibo("+i+")="+f3)
    f1 = f2
    f2 = f3
  EndFor


:Namespace Traps
    ⍝ Traps (exceptions) are just numbers
    ⍝ 500-999 are reserved for the user
    U0 U1←900 901

    ⍝ Catch
    ∇foo;i
        :For i :In ⍳2
            :Trap U0
                bar i
            :Else
                ⎕←'foo caught U0'
            :EndTrap
        :EndFor
    ∇

    ⍝ Throw
    ∇bar i
        ⎕SIGNAL U0 U1[i]
    ∇
:EndNamespace


global U0 := Exception("First Exception")
global U1 := Exception("Second Exception")

foo()

foo(){
	try
		bar()
	catch e
		MsgBox % "An exception was raised: " e.Message
	bar()
}

bar(){
	baz()
}

baz(){
	static calls := 0
	if ( ++calls = 1 )
		throw U0
	else if ( calls = 2 )
		throw U1
}


      REM Allocate error numbers:
      U0& = 123
      U1& = 124

      PROCfoo
      END

      DEF PROCfoo
      ON ERROR LOCAL IF ERR = U0& THEN PRINT "Exception U0 caught in foo" ELSE \
      \              RESTORE ERROR : ERROR ERR, REPORT$
      PROCbar
      PROCbar
      ENDPROC

      DEF PROCbar
      PROCbaz
      ENDPROC

      DEF PROCbaz
      PRIVATE called%
      called% += 1
      CASE called% OF
        WHEN 1: ERROR U0&, "Exception U0 thrown"
        WHEN 2: ERROR U1&, "Exception U1 thrown"
      ENDCASE
      ENDPROC