fileprivate class NumberNames {
    let cardinal: String
    let ordinal: String

    init(cardinal: String, ordinal: String) {
        self.cardinal = cardinal
        self.ordinal = ordinal
    }

    func getName(_ ordinal: Bool) -> String {
        return ordinal ? self.ordinal : self.cardinal
    }

    class func numberName(number: Int, ordinal: Bool) -> String {
        guard number < 100 else {
            return ""
        }
        if number < 20 {
            return smallNames[number].getName(ordinal)
        }
        if number % 10 == 0 {
            return tens[number/10 - 2].getName(ordinal)
        }
        var result = tens[number/10 - 2].getName(false)
        result += "-"
        result += smallNames[number % 10].getName(ordinal)
        return result
    }

    static let smallNames = [
        NumberNames(cardinal: "zero", ordinal: "zeroth"),
        NumberNames(cardinal: "one", ordinal: "first"),
        NumberNames(cardinal: "two", ordinal: "second"),
        NumberNames(cardinal: "three", ordinal: "third"),
        NumberNames(cardinal: "four", ordinal: "fourth"),
        NumberNames(cardinal: "five", ordinal: "fifth"),
        NumberNames(cardinal: "six", ordinal: "sixth"),
        NumberNames(cardinal: "seven", ordinal: "seventh"),
        NumberNames(cardinal: "eight", ordinal: "eighth"),
        NumberNames(cardinal: "nine", ordinal: "ninth"),
        NumberNames(cardinal: "ten", ordinal: "tenth"),
        NumberNames(cardinal: "eleven", ordinal: "eleventh"),
        NumberNames(cardinal: "twelve", ordinal: "twelfth"),
        NumberNames(cardinal: "thirteen", ordinal: "thirteenth"),
        NumberNames(cardinal: "fourteen", ordinal: "fourteenth"),
        NumberNames(cardinal: "fifteen", ordinal: "fifteenth"),
        NumberNames(cardinal: "sixteen", ordinal: "sixteenth"),
        NumberNames(cardinal: "seventeen", ordinal: "seventeenth"),
        NumberNames(cardinal: "eighteen", ordinal: "eighteenth"),
        NumberNames(cardinal: "nineteen", ordinal: "nineteenth")
    ]

    static let tens = [
        NumberNames(cardinal: "twenty", ordinal: "twentieth"),
        NumberNames(cardinal: "thirty", ordinal: "thirtieth"),
        NumberNames(cardinal: "forty", ordinal: "fortieth"),
        NumberNames(cardinal: "fifty", ordinal: "fiftieth"),
        NumberNames(cardinal: "sixty", ordinal: "sixtieth"),
        NumberNames(cardinal: "seventy", ordinal: "seventieth"),
        NumberNames(cardinal: "eighty", ordinal: "eightieth"),
        NumberNames(cardinal: "ninety", ordinal: "ninetieth")
    ]
}

fileprivate class NamedPower {
    let cardinal: String
    let ordinal: String
    let number: UInt64

    init(cardinal: String, ordinal: String, number: UInt64) {
        self.cardinal = cardinal
        self.ordinal = ordinal
        self.number = number
    }

    func getName(_ ordinal: Bool) -> String {
        return ordinal ? self.ordinal : self.cardinal
    }

    class func getNamedPower(_ number: UInt64) -> NamedPower {
        for i in 1..<namedPowers.count {
            if number < namedPowers[i].number {
                return namedPowers[i - 1]
            }
        }
        return namedPowers[namedPowers.count - 1]
    }

    static let namedPowers = [
        NamedPower(cardinal: "hundred", ordinal: "hundredth",
                   number: 100),
        NamedPower(cardinal: "thousand", ordinal: "thousandth",
                   number: 1000),
        NamedPower(cardinal: "million", ordinal: "millionth",
                   number: 1000000),
        NamedPower(cardinal: "billion", ordinal: "billionth",
                   number: 1000000000),
        NamedPower(cardinal: "trillion", ordinal: "trillionth",
                   number: 1000000000000),
        NamedPower(cardinal: "quadrillion", ordinal: "quadrillionth",
                   number: 1000000000000000),
        NamedPower(cardinal: "quintillion", ordinal: "quintillionth",
                   number: 1000000000000000000)
    ]
}

public func numberName(number: UInt64, ordinal: Bool) -> String {
    if number < 100 {
        return NumberNames.numberName(number: Int(truncatingIfNeeded: number),
                                      ordinal: ordinal)
    }
    let p = NamedPower.getNamedPower(number)
    var result = numberName(number: number/p.number, ordinal: false)
    result += " "
    if number % p.number == 0 {
        result += p.getName(ordinal)
    } else {
        result += p.getName(false)
        result += " "
        result += numberName(number: number % p.number, ordinal: ordinal)
    }
    return result
}

func printOrdinal(_ number: UInt64) {
    print("\(number): \(numberName(number: number, ordinal: true))")
}

printOrdinal(1)
printOrdinal(2)
printOrdinal(3)
printOrdinal(4)
printOrdinal(5)
printOrdinal(11)
printOrdinal(15)
printOrdinal(21)
printOrdinal(42)
printOrdinal(65)
printOrdinal(98)
printOrdinal(100)
printOrdinal(101)
printOrdinal(272)
printOrdinal(300)
printOrdinal(750)
printOrdinal(23456)
printOrdinal(7891233)
printOrdinal(8007006005004003)


Private Function ordinal(s As String) As String
    Dim irregs As New Collection
    irregs.Add "first", "one"
    irregs.Add "second", "two"
    irregs.Add "third", "three"
    irregs.Add "fifth", "five"
    irregs.Add "eighth", "eight"
    irregs.Add "ninth", "nine"
    irregs.Add "twelfth", "twelve"
    Dim i As Integer
    For i = Len(s) To 1 Step -1
        ch = Mid(s, i, 1)
        If ch = " " Or ch = "-" Then Exit For
    Next i
    On Error GoTo 1
    ord = irregs(Right(s, Len(s) - i))
    ordinal = Left(s, i) & ord
    Exit Function
1:
    If Right(s, 1) = "y" Then
        s = Left(s, Len(s) - 1) & "ieth"
    Else
        s = s & "th"
    End If
    ordinal = s
End Function
Public Sub ordinals()
    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]
    init
    For i = 1 To UBound(tests)
        Debug.Print ordinal(spell(tests(i)))
    Next i
End Sub


fn main() {
    for n in [i64(1), 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
     ] {
        println(say_ordinal(n))
    }
}

fn say_ordinal(n i64) string {
    mut s := say(n)
    mut i := s.last_index('-') or {s.last_index(' ') or {-1}}
    i++
    // Now s[:i] is everything upto and including the space or hyphen
    // and s[i:] is the last word; we modify s[i:] as required.
    // Since LastIndex returns -1 if there was no space/hyphen,
    // `i` will be zero and this will still be fine.
    ok := s[i..] in irregular_ordinals
    x := irregular_ordinals[s[i..]]
    if ok {
        s = s[..i] + x
    } else if s[s.len-1..s.len] == 'y' {
        s = s[..i] + s[i..s.len-1] + "ieth"
    } else {
        s = s[..i] + s[i..] + "th"
    }
    return s
}

// Below is a copy of https://rosettacode.org/wiki/Number_names#Go

const (
    small = ["zero", "one", "two", "three", "four", "five", "six",
    "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
    "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
    tens = ["", "", "twenty", "thirty", "forty",
    "fifty", "sixty", "seventy", "eighty", "ninety"]
    illions = ["", " thousand", " million", " billion",
    " trillion", " quadrillion", " quintillion"]
    irregular_ordinals = {
        "one":    "first",
        "two":    "second",
        "three":  "third",
        "five":   "fifth",
        "eight":  "eighth",
        "nine":   "ninth",
        "twelve": "twelfth",
    }
)

fn say(nn i64) string {
    mut n := nn
    mut t := ''
    if n < 0 {
        t = "negative "
        // Note, for math.MinInt64 this leaves n negative.
        n = -n
    }
    if n < 20{
        t += small[n]
    } else if n < 100{
        t += tens[n/10]
        s := n % 10
        if s > 0 {
            t += "-" + small[s]
        }
    } else if n < 1000{
        t += small[n/100] + " hundred"
        s := n % 100
        if s > 0 {
            t += " " + say(s)
        }
    } else {
        // work right-to-left
        mut sx := ""
        for i := 0; n > 0; i++ {
            p := n % 1000
            n /= 1000
            if p > 0 {
                mut ix := say(p) + illions[i]
                if sx != "" {
                    ix += " " + sx
                }
                sx = ix
            }
        }
        t += sx
    }
    return t
}


var small = ["zero", "one", "two", "three", "four", "five", "six",  "seven", "eight", "nine", "ten", "eleven",
             "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]

var tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]

var illions = ["", " thousand", " million", " billion"," trillion", " quadrillion", " quintillion"]

var irregularOrdinals = {
    "one":    "first",
    "two":    "second",
    "three":  "third",
    "five":   "fifth",
    "eight":  "eighth",
    "nine":   "ninth",
    "twelve": "twelfth"
}

var say
say = Fn.new { |n|
    var t = ""
    if (n < 0) {
        t = "negative "
        n = -n
    }
    if (n < 20) {
        t = t + small[n]
    } else if (n < 100) {
        t = t + tens[(n/10).floor]
        var s = n % 10
        if (s > 0) t = t + "-" + small[s]
    } else if (n < 1000) {
        t = t + small[(n/100).floor] + " hundred"
        var s = n % 100
        System.write("") // guards against VM recursion bug
        if (s > 0) t = t + " " + say.call(s)
    } else {
        var sx = ""
        var i = 0
        while (n > 0) {
            var p = n % 1000
            n = (n/1000).floor
            if (p > 0) {
                System.write("") // guards against VM recursion bug
                var ix = say.call(p) + illions[i]
                if (sx != "") ix = ix + " " + sx
                sx = ix
            }
            i = i + 1
        }
        t = t + sx
    }
    return t
}

var sayOrdinal = Fn.new { |n|
    var s = say.call(n)
    var r = s[-1..0]
    var i1 = r.indexOf(" ")
    if (i1 != -1) i1 = s.count - 1 - i1
    var i2 = r.indexOf("-")
    if (i2 != -1) i2 = s.count - 1 - i2
    var i = (i1 > i2) ? i1 : i2
    i = i + 1
    // Now s[0...i] is everything up to and including the space or hyphen
	// and s[i..-1] is the last word; we modify s[i..-1] as required.
	// Since indexOf returns -1 if there was no space/hyphen,
	// `i` will be zero and this will still be fine.
    var x = irregularOrdinals[s[i..-1]]
    if (x) {
        return s[0...i] + x
    } else if (s[-1] == "y") {
        return s[0...i] + s[i..-2] + "ieth"
    } else {
        return s[0...i] + s[i..-1] + "th"
    }
}

for (n in [1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 9007199254740991]) {
    System.print(sayOrdinal.call(n))
}


DEFINE MAX_SIZE="10"
DEFINE MAX_MATRIX_SIZE="100"

INT FUNC Index(BYTE size,x,y)
RETURN (x+y*size)

PROC PrintMatrix(BYTE ARRAY a BYTE size)
  BYTE i,j,v

  FOR j=0 TO size-1
  DO
    FOR i=0 TO size-1
    DO
      v=a(Index(size,i,j))
      IF v<10 THEN
        Print("  ")
      ELSE
        Print(" ")
      FI
      PrintB(v)
    OD
    PutE()
  OD
RETURN

PROC FillMatrix(BYTE ARRAY a BYTE size)
  INT lev,maxLev,dist,maxDist,v

  maxLev=size/2
  IF (size&1)=0 THEN
    maxLev==-1
  FI
  maxDist=size-1
  v=1
  FOR lev=0 TO maxLev
  DO
    FOR dist=0 TO maxDist
    DO
      a(Index(size,lev+dist,lev))=v v==+1
    OD
    FOR dist=0 TO maxDist-1
    DO
      a(Index(size,size-1-lev,lev+dist+1))=v v==+1
    OD
    FOR dist=0 TO maxDist-1
    DO
      a(Index(size,size-2-lev-dist,size-1-lev))=v v==+1
    OD
    FOR dist=0 TO maxDist-2
    DO
      a(Index(size,lev,size-2-lev-dist))=v v==+1
    OD
    maxDist==-2
  OD
RETURN

PROC Test(BYTE size)
  BYTE ARRAY mat(MAX_MATRIX_SIZE)

  PrintF("Matrix size: %B%E",size)
  FillMatrix(mat,size)
  PrintMatrix(mat,size)
  PutE()
RETURN

PROC Main()
  Test(5)
  Test(6)
RETURN


-- Spiral Square
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;

procedure Spiral_Square is
   type Array_Type is array(Positive range <>, Positive range <>) of Natural;

   function Spiral (N : Positive) return Array_Type is
      Result  : Array_Type(1..N, 1..N);
      Row     : Natural := 1;
      Col     : Natural := 1;
      Max_Row : Natural := N;
      Max_Col : Natural := N;
      Min_Row : Natural := 1;
      Min_Col : Natural := 1;
   begin
      for I in 0..N**2 - 1 loop
         Result(Row, Col) := I;
         if Row = Min_Row then
            Col := Col + 1;
            if Col > Max_Col then
               Col := Max_Col;
               Row := Row + 1;
            end if;
         elsif Col = Max_Col then
            Row := Row + 1;
            if Row > Max_Row then
               Row := Max_Row;
               Col := Col - 1;
            end if;
         elsif Row = Max_Row then
            Col := Col - 1;
            if Col < Min_Col then
               Col := Min_Col;
               Row := Row - 1;
            end if;
         elsif Col = Min_Col then
            Row := Row - 1;
            if Row = Min_Row then  -- Reduce spiral
               Min_Row := Min_Row + 1;
               Max_Row := Max_Row - 1;
               Row := Min_Row;
               Min_Col := Min_Col + 1;
               Max_Col := Max_Col - 1;
               Col := Min_Col;
            end if;
         end if;
      end loop;
      return Result;
   end Spiral;

   procedure Print(Item : Array_Type) is
      Num_Digits : constant Float := Log(X => Float(Item'Length(1)**2), Base => 10.0);
      Spacing    : constant Positive := Integer(Num_Digits) + 2;
   begin
      for I in Item'range(1) loop
         for J in Item'range(2) loop
            Put(Item => Item(I,J), Width => Spacing);
         end loop;
         New_Line;
      end loop;
   end Print;

begin
   Print(Spiral(5));
end Spiral_Square;


      STACKSIZE = 1000

      FOR n = 3 TO 5
        PRINT "Push ";n : PROCpush(n)
      NEXT
      PRINT "Pop " ; FNpop
      PRINT "Push 6" : PROCpush(6)
      REPEAT
        PRINT "Pop " ; FNpop
      UNTIL FNisempty
      PRINT "Pop " ; FNpop
      END

      DEF PROCpush(n) : LOCAL f%
      DEF FNpop : LOCAL f% : f% = 1
      DEF FNisempty : LOCAL f% : f% = 2
      PRIVATE stack(), sptr%
      DIM stack(STACKSIZE-1)
      CASE f% OF
        WHEN 0:
          IF sptr% = DIM(stack(),1) ERROR 100, "Error: stack overflowed"
          stack(sptr%) = n
          sptr% += 1
        WHEN 1:
          IF sptr% = 0 ERROR 101, "Error: stack empty"
          sptr% -= 1
          = stack(sptr%)
        WHEN 2:
          = (sptr% = 0)
      ENDCASE
      ENDPROC


     instruction: _f

     gstack:      UInt64[0]•         (at the beginning of a program lstack is initialized to [0 0 0]


fcn nth(n,th=True){
   var [const]
     nmsth=T("","first","second","third","fourth","fifth","sixth","seventh","eighth","ninth"),
     nms1=T("","one","two","three","four","five","six","seven","eight","nine"),
     nms10=T("ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"),
     nms10th=T("tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"),
     nms20=T("twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"),
     nms1000=T("thousand","million","billion","trillion","quadrillion"); // 3,6,9,12,15

   if     (n<0)  String("negative ",nth(-n,th));
   else if(n<10) th and nmsth[n] or nms1[n];
   else if(n<20) th and nms10th[n-10] or nms10[n-10];
   else if(n<10) th and nmsth[n] or nms1[n];
   else if(n<100){
      m,txt := n%10,nms20[n/10-2];
      if(m) String(txt,dash(n%10,"-",th));
      else  String(txt[0,-1],"ieth");
   }
   else if(n<1000) String(nms1[n/100]," hundred",dash(n%100," ",th));
   else{
      n=n.toInt();   // yuck, only here to handle floats, 1.23-->"first"
      ds:=(n.numDigits()-1)/3*3; // 1e3->3, 1e4-->3, 1e5-->3, 1e6-->6, 1e7-->6
      z:=(10).pow(ds);  // 1234-->1000, 12345-->10000
      thou:=ds/3 - 1;	// 1000-->0, 10000-->0, 2,000,000-->1
      nnn,ys := n/z, n%z;
      String((if(nnn<10) nms1[nnn] else nth(nnn,False)),
	  " ",nms1000[thou],
	  if(ys==0) "th" else String(" ",nth(ys,th)));
   }
}
fcn dash(n,d,th){ if(n) String(d,nth(n,th)) else (th and "th" or "") }


INT empty=0;

PROC spiral = (INT n)[,]INT: (
    INT dx:=1, dy:=0;            # Starting increments #
    INT x:=0, y:=0;              # Starting location #
    [0:n-1,0:n-1]INT my array;
    FOR y FROM LWB my array TO UPB my array DO
        FOR x FROM LWB my array TO UPB my array DO
            my array[x,y]:=empty
        OD
    OD;
    FOR i TO n**2 DO
        my array[x,y] := i;
        INT nx:=x+dx, ny:=y+dy;
        IF ( 0<=nx AND nx<n AND 0<=ny AND ny<n | my array[nx,ny] = empty | FALSE ) THEN
            x:=nx; y:=ny
        ELSE
            INT swap:=dx; dx:=-dy; dy:=swap;
            x+:=dx; y+:=dy
        FI
    OD;
    my array
);

PROC print spiral = ([,]INT my array)VOID:(
    FOR y FROM LWB my array TO UPB my array DO
        FOR x FROM LWB my array TO UPB my array DO
            print(whole(my array[x,y],-3))
        OD;
        print(new line)
    OD
);

print spiral(spiral(5))


    Push ← ∾
∾
   Pop ← ¯1⊸↓
¯1⊸↓
   Empty ← 0=≠
0=≠
   1‿2‿3 Push 4
⟨ 1 2 3 4 ⟩
   Pop 1‿2‿3
⟨ 1 2 ⟩
   Empty 1‿2‿3
0
   Empty ⟨⟩
1


( ( stack
  =   (S=)
      (push=.(!arg.!(its.S)):?(its.S))
      ( pop
      = top.!(its.S):(%?top.?(its.S))&!top
      )
      (top=top.!(its.S):(%?top.?)&!top)
      (empty=.!(its.S):)
  )
& new$stack:?Stack
& (Stack..push)$(2*a)
& (Stack..push)$pi
& (Stack..push)$
& (Stack..push)$"to be or"
& (Stack..push)$"not to be"
& out$((Stack..pop)$|"Cannot pop (a)")
& out$((Stack..top)$|"Cannot pop (b)")
& out$((Stack..pop)$|"Cannot pop (c)")
& out$((Stack..pop)$|"Cannot pop (d)")
& out$((Stack..pop)$|"Cannot pop (e)")
& out$((Stack..pop)$|"Cannot pop (f)")
& out$((Stack..pop)$|"Cannot pop (g)")
& out$((Stack..pop)$|"Cannot pop (h)")
&   out
  $ ( str
    $ ( "Stack is "
        ((Stack..empty)$&|not)
        " empty"
      )
    )
&
);


---------------------- SPIRAL MATRIX ---------------------

-- spiral :: Int -> [[Int]]
on spiral(n)
    script go
        on |λ|(rows, cols, start)
            if 0 < rows then
                {enumFromTo(start, start + pred(cols))} & ¬
                    map(my |reverse|, ¬
                        transpose(|λ|(cols, pred(rows), start + cols)))
            else
                {{}}
            end if
        end |λ|
    end script

    go's |λ|(n, n, 0)
end spiral

--------------------------- TEST -------------------------
on run
    wikiTable(spiral(5), ¬
        false, ¬
        "text-align:center;width:12em;height:12em;table-layout:fixed;")
end run

-------------------- WIKI TABLE FORMAT -------------------

-- wikiTable :: [Text] -> Bool -> Text -> Text
on wikiTable(lstRows, blnHdr, strStyle)
    script fWikiRows
        on |λ|(lstRow, iRow)
            set strDelim to if_(blnHdr and (iRow = 0), "!", "|")
            set strDbl to strDelim & strDelim
            linefeed & "|-" & linefeed & strDelim & space & ¬
                intercalateS(space & strDbl & space, lstRow)
        end |λ|
    end script

    linefeed & "{| class=\"wikitable\" " & ¬
        if_(strStyle ≠ "", "style=\"" & strStyle & "\"", "") & ¬
        intercalateS("", ¬
            map(fWikiRows, lstRows)) & linefeed & "|}" & linefeed
end wikiTable

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

-- comparing :: (a -> b) -> (a -> a -> Ordering)
on comparing(f)
    script
        on |λ|(a, b)
            tell mReturn(f)
                set fa to |λ|(a)
                set fb to |λ|(b)
                if fa < fb then
                    -1
                else if fa > fb then
                    1
                else
                    0
                end if
            end tell
        end |λ|
    end script
end comparing

-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
    set lng to length of xs
    set acc to {}
    tell mReturn(f)
        repeat with i from 1 to lng
            set acc to acc & (|λ|(item i of xs, i, xs))
        end repeat
    end tell
    if {text, string} contains class of xs then
        acc as text
    else
        acc
    end if
end concatMap

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

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

-- if_ :: Bool -> a -> a -> a
on if_(bool, x, y)
    if bool then
        x
    else
        y
    end if
end if_

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

-- length :: [a] -> Int
on |length|(xs)
    length of xs
end |length|

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

-- maximumBy :: (a -> a -> Ordering) -> [a] -> a
on maximumBy(f, xs)
    set cmp to mReturn(f)
    script max
        on |λ|(a, b)
            if a is missing value or cmp's |λ|(a, b) < 0 then
                b
            else
                a
            end if
        end |λ|
    end script

    foldl(max, missing value, xs)
end maximumBy

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

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

-- pred :: Enum a => a -> a
on pred(x)
    x - 1
end pred

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

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

-- reverse :: [a] -> [a]
on |reverse|(xs)
    if class of xs is text then
        (reverse of characters of xs) as text
    else
        reverse of xs
    end if
end |reverse|

-- Simplified version - assuming rows of unvarying length.
-- transpose :: [[a]] -> [[a]]
on transpose(rows)
    script cols
        on |λ|(_, iCol)
            script cell
                on |λ|(row)
                    item iCol of row
                end |λ|
            end script
            concatMap(cell, rows)
        end |λ|
    end script
    map(cols, item 1 of rows)
end transpose

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

-- unwords :: [String] -> String
on unwords(xs)
    intercalateS(space, xs)
end unwords


stack = []
stack.push 1
stack.push 2
stack.push 3

until { stack.empty? } { p stack.pop }


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

/* to read expanded code, run through cpp | indent -st */
#define DECL_STACK_TYPE(type, name)					\
typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;	\
stk_##name stk_##name##_create(size_t init_size) {			\
	stk_##name s; if (!init_size) init_size = 4;			\
	s = malloc(sizeof(struct stk_##name##_t));			\
	if (!s) return 0;						\
	s->buf = malloc(sizeof(type) * init_size);			\
	if (!s->buf) { free(s); return 0; }				\
	s->len = 0, s->alloc = init_size;				\
	return s; }							\
int stk_##name##_push(stk_##name s, type item) {			\
	type *tmp;							\
	if (s->len >= s->alloc) {					\
		tmp = realloc(s->buf, s->alloc*2*sizeof(type));		\
		if (!tmp) return -1; s->buf = tmp;			\
		s->alloc *= 2; }					\
	s->buf[s->len++] = item;					\
	return s->len; }						\
type stk_##name##_pop(stk_##name s) {					\
	type tmp;							\
	if (!s->len) abort();						\
	tmp = s->buf[--s->len];						\
	if (s->len * 2 <= s->alloc && s->alloc >= 8) {			\
		s->alloc /= 2;						\
		s->buf = realloc(s->buf, s->alloc * sizeof(type));}	\
	return tmp; }							\
void stk_##name##_delete(stk_##name s) {				\
	free(s->buf); free(s); }

#define stk_empty(s) (!(s)->len)
#define stk_size(s) ((s)->len)

DECL_STACK_TYPE(int, int)

int main(void)
{
	int i;
	stk_int stk = stk_int_create(0);

	printf("pushing: ");
	for (i = 'a'; i <= 'z'; i++) {
		printf(" %c", i);
		stk_int_push(stk, i);
	}

	printf("\nsize now: %d", stk_size(stk));
	printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");

	printf("\npoppoing:");
	while (stk_size(stk))
		printf(" %c", stk_int_pop(stk));
	printf("\nsize now: %d", stk_size(stk));
	printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");

	/* stk_int_pop(stk); <-- will abort() */
	stk_int_delete(stk);
	return 0;
}


spiralMatrix: function [n][
    m: new array.of: @[n,n] null

    [dx, dy, x, y]: [1, 0, 0, 0]

    loop 0..dec n^2 'i [
        m\[y]\[x]: i

        [nx,ny]: @[x+dx, y+dy]

        if? and? [and? [in? nx 0..n-1][in? ny 0..n-1]][
            null? m\[ny]\[nx]
        ][
            [x,y]: @[nx, ny]
        ]
        else [
            bdx: dx
            [dx, dy]: @[neg dy, bdx]
            [x, y]: @[x+dx, y+dy]
        ]
    ]

    return m
]

loop spiralMatrix 5 'row [
    print map row 'x -> pad to :string x 4
]


// Non-Generic Stack
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek(); // Peek without Popping.
top = stack.Pop();

// Generic Stack
System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek(); // Peek without Popping.
top = stack.Pop();


(deftype Stack [elements])

(def stack (Stack (ref ())))

(defn push-stack
  "Pushes an item to the top of the stack."
  [x] (dosync (alter (:elements stack) conj x)))

(defn pop-stack
  "Pops an item from the top of the stack."
  [] (let [fst (first (deref (:elements stack)))]
       (dosync (alter (:elements stack) rest)) fst))

(defn top-stack
  "Shows what's on the top of the stack."
  [] (first (deref (:elements stack))))

(defn empty-stack?
  "Tests whether or not the stack is empty."
  [] (= () (deref (:elements stack))))


% Stack
stack = cluster [T: type] is new, push, pop, peek, empty
    rep = array[T]

    new = proc () returns (cvt)
        return (rep$new())
    end new

    empty = proc (s: cvt) returns (bool)
        return (rep$size(s) = 0)
    end empty;

    push = proc (s: cvt, val: T)
        rep$addh(s, val)
    end push;

    pop = proc (s: cvt) returns (T) signals (empty)
        if rep$empty(s)
            then signal empty
            else return(rep$remh(s))
        end
    end pop

    peek = proc (s: cvt) returns (T) signals (empty)
        if rep$empty(s)
            then signal empty
            else return(s[rep$high(s)])
        end
    end peek
end stack

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

    % Make a stack
    s: stack[int] := stack[int]$new()

    % Push 1..10 onto the stack
    for i: int in int$from_to(1, 10) do
        stack[int]$push(s, i)
    end

    % Pop items off the stack until the stack is empty
    while ~stack[int]$empty(s) do
        stream$putl(po, int$unparse(stack[int]$pop(s)))
    end

    % Trying to pop off the stack now should raise 'empty'
    begin
        i: int := stack[int]$pop(s)
        stream$putl(po, "Still here! And I got: " || int$unparse(i))
    end except when empty:
        stream$putl(po, "The stack is empty.")
    end
end start_up


# syntax: GAWK -f SPIRAL_MATRIX.AWK [-v offset={0|1}] [size]
# converted from BBC BASIC
BEGIN {
# offset: "0" prints 0 to size^2-1 while "1" prints 1 to size^2
    offset = (offset == "") ? 0 : offset
    size = (ARGV[1] == "") ? 5 : ARGV[1]
    if (offset !~ /^[01]$/) { exit(1) }
    if (size !~ /^[0-9]+$/) { exit(1) }
    bot_col = bot_row = 0
    top_col = top_row = size - 1
    direction = col = row = 0
    for (i=0; i<=size*size-1; i++) { # build
      arr[col,row] = i + offset
      if (direction == 0) {
        if (col < top_col) { col++ }
        else { direction = 1 ; row++ ; bot_row++ }
      }
      else if (direction == 1) {
        if (row < top_row) { row++ }
        else { direction = 2 ; col-- ; top_col-- }
      }
      else if (direction == 2) {
        if (col > bot_col) { col-- }
        else { direction = 3 ; row-- ; top_row-- }
      }
      else if (direction == 3) {
        if (row > bot_row) { row-- }
        else { direction = 0 ; col++ ; bot_col++ }
      }
    }
    width = length(size ^ 2 - 1 + offset) + 1 # column width
    for (i=0; i<size; i++) { # print
      for (j=0; j<size; j++) {
        printf("%*d",width,arr[j,i])
      }
      printf("\n")
    }
    exit(0)
}


       01  stack.
         05  head USAGE IS POINTER VALUE NULL.


stack = []
stack.push 1
stack.push 2
console.log stack
console.log stack.pop()
console.log stack


      N%=5
      @%=LENSTR$(N%*N%-1)+1
      BotCol%=0 : TopCol%=N%-1
      BotRow%=0 : TopRow%=N%-1
      DIM Matrix%(TopCol%,TopRow%)

      Dir%=0 : Col%=0 : Row%=0
      FOR I%=0 TO N%*N%-1
        Matrix%(Col%,Row%)=I%
        PRINT TAB(Col%*@%,Row%) I%
        CASE Dir% OF
          WHEN 0: IF Col% < TopCol% THEN Col%+=1 ELSE Dir%=1 : Row%+=1 : BotRow%+=1
          WHEN 1: IF Row% < TopRow% THEN Row%+=1 ELSE Dir%=2 : Col%-=1 : TopCol%-=1
          WHEN 2: IF Col% > BotCol% THEN Col%-=1 ELSE Dir%=3 : Row%-=1 : TopRow%-=1
          WHEN 3: IF Row% > BotRow% THEN Row%-=1 ELSE Dir%=0 : Col%+=1 : BotCol%+=1
        ENDCASE
      NEXT
      END


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

#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]
int main(int c, char **v)
{
	int i, j, m = 0, n = 0;

	/* default size: 5 */
	if (c >= 2) m = atoi(v[1]);
	if (c >= 3) n = atoi(v[2]);
	if (m <= 0) m = 5;
	if (n <= 0) n = m;

	int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);
	s[0] = (int*)(s + m);
	for (i = 1; i < m; i++) s[i] = s[i - 1] + n;

	int dx = 1, dy = 0, val = 0, t;
	for (i = j = 0; valid(i, j); i += dy, j += dx ) {
		for (; valid(i, j); j += dx, i += dy)
			s[i][j] = ++val;

		j -= dx; i -= dy;
		t = dy; dy = dx; dx = -t;
	}

	for (t = 2; val /= 10; t++);

	for(i = 0; i < m; i++)
		for(j = 0; j < n || !putchar('\n'); j++)
			printf("%*d", t, s[i][j]);

	return 0;
}


(defstruct stack
  elements)

(defun stack-push (element stack)
  (push element (stack-elements stack)))

(defun stack-pop (stack)(deftype Stack [elements])

(defun stack-empty (stack)
  (endp (stack-elements stack)))

(defun stack-top (stack)
  (first (stack-elements stack)))

(defun stack-peek (stack)
  (stack-top stack))


MODULE Stacks;
IMPORT StdLog;

TYPE
	(* some pointers to records *)
	Object* = POINTER TO ABSTRACT RECORD END;

	Integer = POINTER TO RECORD (Object)
		i: INTEGER
	END;

	Point = POINTER TO RECORD (Object)
		x,y: REAL
	END;

	Node = POINTER TO LIMITED RECORD
		next- : Node;
		data-: ANYPTR;
	END;

	(* Stack *)
	Stack* = POINTER TO RECORD
		top- : Node;
	END;

	PROCEDURE (dn: Object) Show*, NEW, ABSTRACT;

	PROCEDURE (i: Integer) Show*;
	BEGIN
		StdLog.String("Integer(");StdLog.Int(i.i);StdLog.String(");");StdLog.Ln
	END Show;

	PROCEDURE (p: Point) Show*;
	BEGIN
		StdLog.String("Point(");StdLog.Real(p.x);StdLog.Char(',');
		StdLog.Real(p.y);StdLog.String(");");StdLog.Ln
	END Show;

	PROCEDURE (s: Stack) Init, NEW;
	BEGIN
		s.top := NIL;
	END Init;

	PROCEDURE (s: Stack) Push*(data: ANYPTR), NEW;
	VAR
		n: Node;
	BEGIN
		NEW(n);n.next := NIL;n.data := data;
		IF s.top = NIL THEN
			s.top := n
		ELSE
			n.next := s.top;
			s.top := n
		END
	END Push;

	PROCEDURE (s: Stack) Pop*(): ANYPTR, NEW;
	VAR
		x: ANYPTR;
	BEGIN
		IF s.top # NIL THEN
			x := s.top.data;
			s.top := s.top.next
		ELSE
			x := NIL
		END;
		RETURN x
	END Pop;

	PROCEDURE (s: Stack) Empty*(): BOOLEAN, NEW;
	BEGIN
		RETURN s.top = NIL
	END Empty;

	PROCEDURE NewStack*(): Stack;
	VAR
		s: Stack;
	BEGIN
		NEW(s);s.Init;
		RETURN s
	END NewStack;

	PROCEDURE NewInteger*(data: INTEGER): Integer;
	VAR
		i: Integer;
	BEGIN
		NEW(i);i.i := data;
		RETURN i
	END NewInteger;

	PROCEDURE NewPoint*(x,y: REAL): Point;
	VAR
		p: Point;
	BEGIN
		NEW(p);p.x := x;p.y := y;
		RETURN p
	END NewPoint;

	PROCEDURE TestStack*;
	VAR
		s: Stack;
	BEGIN
		s := NewStack();
		s.Push(NewInteger(1));
		s.Push(NewPoint(2.0,3.4));
		s.Pop()(Object).Show();
		s.Pop()(Object).Show();
	END TestStack;

END Stacks.


;DEFINING INTERRUPT VECTORS ON THE NES
org $FFFA
dw #### ;address of your NMI handler goes here (you can use labels for each of these for your convenience)
dw #### ;address of your Reset handler goes here
dw #### ;address of your IRQ handler goes here.


public int[,] Spiral(int n) {
    int[,] result = new int[n, n];

    int pos = 0;
    int count = n;
    int value = -n;
    int sum = -1;

    do {
        value = -1 * value / n;
        for (int i = 0; i < count; i++) {
            sum += value;
            result[sum / n, sum % n] = pos++;
        }
        value *= n;
        count--;
        for (int i = 0; i < count; i++) {
            sum += value;
            result[sum / n, sum % n] = pos++;
        }
    } while (count > 0);

    return result;
}

// Method to print arrays, pads numbers so they line up in columns
public void PrintArray(int[,] array) {
    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;

    for (int i = 0; i < array.GetLength(0); i++) {
        for (int j = 0; j < array.GetLength(1); j++) {
            Console.Write(array[i, j].ToString().PadLeft(n, ' '));
        }
        Console.WriteLine();
    }
}


stack = [] of Int32
(1..10).each do |x|
  stack.push x
end

10.times do
  puts stack.pop
end


import std.array;

class Stack(T) {
    private T[] items;

    @property bool empty() { return items.empty(); }

    void push(T top) { items ~= top; }

    T pop() {
        if (this.empty)
            throw new Exception("Empty Stack.");
        auto top = items.back;
        items.popBack();
        return top;
    }
}

void main() {
    auto s = new Stack!int();
    s.push(10);
    s.push(20);
    assert(s.pop() == 20);
    assert(s.pop() == 10);
    assert(s.empty());
}


#!/usr/local/bin/a68g --script #

FORMAT f = $g": ["g"]"l$;

printf((f,
  "pi", pi,
  "random", random, # actually a procedure #

  "flip", flip,
  "flop", flop,
  "TRUE", TRUE,
  "FALSE", FALSE,

  "error char", error char,
  "null character", null character,
CO   "NIL", NIL, NIL is not printable END CO

# "lengths" details how many distinctive precisions are permitted. #
# e.g. int length = 3 suggests 3 distincts types: #
#      INT, LONG INT, and LONG LONG INT #
  "bits shorths", bits shorths,
  "bits lengths", bits lengths,
  "bytes shorths", bytes shorths,
  "bytes lengths", bytes lengths,
  "int shorths", int shorths,
  "int lengths", int lengths,
  "real shorths", real shorths,
  "real lengths", real lengths,

  "max abs char", max abs char,
# short/long int/real also possible #
  "max int", max int,
  "small real", small real,
  "max real", max real,

# "width" indicates how many characters are require to prepresent the value #
# short/long bits/bytes/int/real also possible #
  "bits width", bits width,
  "bytes width", bytes width,
  "int width", int width,
  "real width", real width,
  "exp width", exp width
));

# ALL the following are actually procedures #
print((
  "space: [", space, "]", new line,
  "new line: [", new line, "]", new line,
  "new page: [", new page, "]", new line
CO the following are standard, but not implemented in algol68g
  "char number: [", char number, "]", new line,
  "line number: [", line number, "]", new line,
  "page number: [", page number, "]", new line
END CO
));
SKIP


#include <vector>
#include <memory>	// for auto_ptr
#include <cmath>	// for the ceil and log10 and floor functions
#include <iostream>
#include <iomanip>	// for the setw function

using namespace std;

typedef vector< int > IntRow;
typedef vector< IntRow > IntTable;

auto_ptr< IntTable > getSpiralArray( int dimension )
{
	auto_ptr< IntTable > spiralArrayPtr( new IntTable(
		dimension, IntRow( dimension ) ) );

	int numConcentricSquares = static_cast< int >( ceil(
		static_cast< double >( dimension ) / 2.0 ) );

	int j;
	int sideLen = dimension;
	int currNum = 0;

	for ( int i = 0; i < numConcentricSquares; i++ )
	{
		// do top side
		for ( j = 0; j < sideLen; j++ )
			( *spiralArrayPtr )[ i ][ i + j ] = currNum++;

		// do right side
		for ( j = 1; j < sideLen; j++ )
			( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;

		// do bottom side
		for ( j = sideLen - 2; j > -1; j-- )
			( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;

		// do left side
		for ( j = sideLen - 2; j > 0; j-- )
			( *spiralArrayPtr )[ i + j ][ i ] = currNum++;

		sideLen -= 2;
	}

	return spiralArrayPtr;
}

void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )
{
	size_t dimension = spiralArrayPtr->size();

	int fieldWidth = static_cast< int >( floor( log10(
		static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;

	size_t col;
	for ( size_t row = 0; row < dimension; row++ )
	{
		for ( col = 0; col < dimension; col++ )
			cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];
		cout << endl;
	}
}

int main()
{
	printSpiralArray( getSpiralArray( 5 ) );
}


program Stack;

{$APPTYPE CONSOLE}

uses Generics.Collections;

var
  lStack: TStack<Integer>;
begin
  lStack := TStack<Integer>.Create;
  try
    lStack.Push(1);
    lStack.Push(2);
    lStack.Push(3);
    Assert(lStack.Peek = 3); // 3 should be at the top of the stack

    Writeln(lStack.Pop); // 3
    Writeln(lStack.Pop); // 2
    Writeln(lStack.Pop); // 1
    Assert(lStack.Count = 0); // should be empty
  finally
    lStack.Free;
  end;
end.


% the Algol W standard environment includes the following standard variables: %

integer                I_W          % field width for integer output %
integer                R_W          % field width for real output %
integer                R_D          % number of decimal places for real output %
string(1)              R_FORMAT     % format for real output:
                                          S - "scaled" normalised mantissa with exponent
                                          A - "aligned" fixed point format
                                          F - "free" either scaled or aligned as appropriate
                                                     for the value and field width
                                    %
integer                S_W          % separator width - number of spaces following non-string output items %
integer                MAXINTEGER   % largest integer value %
real                   EPSILON      % largest positive real number such that 1 + epsilon = 1 %
long real              LONGEPSILON  % largest positive long real number such that 1 + longepsilon = 1 %
long real              MAXREAL      % largest real number %
long real              PI           % approximation to pi %

% the following reference(EXCEPTION) variables control how errors are handled:
    ENDFILE                         - end-of-file
    OVFL                            - overflow
    UNFL                            - underflow
    DIVZERO                         - division by zero
    INTOVFL                         - integer overflow
    INTDIVZERO                      - integer division by zero or modulo 0
    SQRTERR                         - invalid SQRT parameter
    EXPERR                          - invalid EXP parameter
    LNLOGERR                        - invalid LN or LOG parameter
    SINCOSERR                       - invalid SIN or COS parameter

The EXCEPTION record is defined as follows:

record    EXCEPTION( logical    XCPNOTED      - true if the exception has occurred
                   ; integer    XCPLIMIT      - number of times the exception can occur
                                                before the program terminates
                              , XCPACTION     - if the program continues, controls how to
                                                replace the erroneous value
                   ; logical    XCPMARK       - true if an error message should be printed
                                                even if the program continues
                   ; string(64) XCPMSG        - message to describe the exception
                   )

if the relevant EXCEPTION variable is null, the exception is ignored,
otherwise it is processed according to the settings of XCPLIMIT etc.
%


%CD% - expands to the current directory string.

%DATE% - expands to current date using same format as DATE command.

%TIME% - expands to current time using same format as TIME command.

%RANDOM% - expands to a random decimal number between 0 and 32767.

%ERRORLEVEL% - expands to the current ERRORLEVEL value

%CMDEXTVERSION% - expands to the current Command Processor Extensions
    version number.

%CMDCMDLINE% - expands to the original command line that invoked the
    Command Processor.

%HIGHESTNUMANODENUMBER% - expands to the highest NUMA node number
    on this machine.


(defn spiral [n]
  (let [cyc (cycle [1 n -1 (- n)])]
    (->> (range (dec n) 0 -1)
         (mapcat #(repeat 2 %))
         (cons n)
         (mapcat #(repeat %2 %) cyc)
         (reductions +)
         (map vector (range 0 (* n n)))
         (sort-by second)
         (map first)))

(let [n 5]
  (clojure.pprint/cl-format
    true
    (str " ~{~<~%~," (* n 3) ":;~2d ~>~}~%")
    (spiral n)))


var stack: array of Integer;

stack.Push(1);
stack.Push(2);
stack.Push(3);

PrintLn(stack.Pop); // 3
PrintLn(stack.Pop); // 2
PrintLn(stack.Pop); // 1

Assert(stack.Length = 0); // assert empty


type Stack() {
    var xs = []
}

func Stack.IsEmpty() => this!xs.Length() == 0

func Stack.Peek() => this!xs[this!xs.Length() - 1]

func Stack.Pop() {
    var e = this!xs[this!xs.Length() - 1]
    this!xs.RemoveAt(this!xs.Length() - 1)
    return e
}

func Stack.Push(item) => this!xs.Add(item)

var stack = Stack()
stack.Push(1)
stack.Push(2)
print(stack.Pop())
print(stack.Peek())
stack.Pop()
print(stack.IsEmpty())


@%        The number output format control variable
@cmd$     The command line of a 'compiled' program
@dir$     The directory (folder) from which the program was loaded
@flags%   An integer incorporating BBC BASIC's control flags
@hcsr%    The handle of the mouse pointer (cursor)
@haccel%  The handle of the keyboard accelerator, if used
@hevent%  The handle of the event used to prevent blocking in serial I/O
@hfile%() An array of file handles indexed by channel number
@hmdi%    The Multiple Document Interface window handle (if any)
@hwacc%   The window handle to which keyboard accelerator commands should be sent
@hwnd%    The 'window handle' for the main (output) window
@hwo%     The handle of the WAVEOUTPUT device
@hpal%    The handle for the colour palette
@ispal%   A Boolean which is non-zero if the display is paletted
@lib$     The directory (folder) containing the library files
@lparam%  The LPARAM value (for use with ON MOUSE, ON MOVE and ON SYS)
@memhdc%  The 'device context' for the main (output) window
@midi%    The MIDI device ID (non-zero if a MIDI file is playing)
@msg%     The MSG value (for use with ON MOUSE, ON MOVE and ON SYS)
@ox%      The horizontal offset (in pixels) between the output bitmap and the window contents
@oy%      The vertical offset (in pixels) between the output bitmap and the window contents
@prthdc%  The 'device context' for the current printer (if any)
@tmp$     The temporary directory (folder)
@usr$     The user's Documents directory (folder)
@vdu%     A pointer to the text and graphics parameters
@vdu{}    A structure containing the main text and graphics variables
@wparam%  The WPARAM value (for use with ON MOUSE, ON MOVE and ON SYS)


#include <iostream>

struct SpecialVariables
{
    int i = 0;

    SpecialVariables& operator++()
    {
        // 'this' is a special variable that is a pointer to the current
        // class instance.  It can optionally be used to refer to elements
        // of the class.
        this->i++;  // has the same meaning as 'i++'

        // returning *this lets the object return a reference to itself
        return *this;
    }

};

int main()
{
    SpecialVariables sv;
    auto sv2 = ++sv;     // makes a copy of sv after it was incremented
    std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n";
}


# Let's say you want to arrange the first N-squared natural numbers
# in a spiral, where you fill in the numbers clockwise, starting from
# the upper left corner.  This code computes the values for each x/y
# coordinate of the square.  (Of course, you could precompute the values
# iteratively, but what fun is that?)

spiral_value = (x, y, n) ->
  prior_legs =
    N: 0
    E: 1
    S: 2
    W: 3

  edge_run = (edge_offset) ->
    N: -> edge_offset.W - edge_offset.N
    E: -> edge_offset.N - edge_offset.E
    S: -> edge_offset.E - edge_offset.S
    W: -> edge_offset.S - edge_offset.W

  edge_offset =
    N: y
    E: n - 1 - x
    S: n - 1 - y
    W: x

  min_edge_offset = n
  for dir of edge_offset
    if edge_offset[dir] < min_edge_offset
      min_edge_offset = edge_offset[dir]
      border = dir

  inner_square_edge = n - 2 * min_edge_offset
  corner_offset = n * n - inner_square_edge * inner_square_edge
  corner_offset += prior_legs[border] * (inner_square_edge - 1)
  corner_offset + edge_run(edge_offset)[border]()

spiral_matrix = (n) ->
  # return a nested array expression
  for y in [0...n]
    for x in [0...n]
      spiral_value x, y, n

do ->
  for n in [6, 7]
    console.log "\n----Spiral n=#{n}"
    console.log spiral_matrix n


local :stack [] #lists used to be stacks in DV

push-to stack 1
push-to stack 2
push-to stack 3

!. pop-from stack #prints 3
!. pop-from stack #prints 2
!. pop-from stack #prints 1

if stack: #empty lists are falsy
    error #this stack should be empty now!


? def l := [].diverge()
# value: [].diverge()

? l.push(1)
? l.push(2)
? l
# value: [1, 2].diverge()

? l.pop()
# value: 2

? l.size().aboveZero()
# value: true

? l.last()
# value: 1

? l.pop()
# value: 1

? l.size().aboveZero()
# value: false


(apply str (interpose " " (sort (filter #(.startsWith % "*") (map str (keys (ns-publics 'clojure.core)))))))


(defun special-variables ()
  (flet ((special-var-p (s)
           (and (char= (aref s 0) #\*)
                (find-if-not (lambda (x) (char= x #\*)) s)
                (char= (aref s (1- (length s))) #\*))))
    (let ((lst '()))
      (do-symbols (s (find-package 'cl))
        (when (special-var-p (symbol-name s))
          (push s lst)))
      lst)))

(format t "~a~%" (sort (special-variables) #'string<))


func Integer.Double() {
    this + this
}
print(8.Double())


(defun spiral (rows columns)
  (do ((N (* rows columns))
       (spiral (make-array (list rows columns) :initial-element nil))
       (dx 1) (dy 0) (x 0) (y 0)
       (i 0 (1+ i)))
      ((= i N) spiral)
    (setf (aref spiral y x) i)
    (let ((nx (+ x dx)) (ny (+ y dy)))
      (cond
       ((and (< -1 nx columns)
             (< -1 ny rows)
             (null (aref spiral ny nx)))
        (setf x nx
              y ny))
       (t (psetf dx (- dy)
                 dy dx)
          (setf x (+ x dx)
                y (+ y dy)))))))


; build stack [0 1 ... 9 (top)] from a list
(list->stack (iota 10) 'my-stack)
(stack-top 'my-stack) → 9
(pop 'my-stack)  → 9
(stack-top 'my-stack) → 8
(push 'my-stack '🐸) ; any kind of lisp object in the stack
(stack-empty? 'my-stack) → #f
(stack->list 'my-stack) ; convert stack to list
    → (0 1 2 3 4 5 6 7 8 🐸)
(stack-swap 'my-stack) ; swaps two last items
    → 8 ; new top
(stack->list 'my-stack)
     → (0 1 2 3 4 5 6 7 🐸 8) ; swapped
(while (not (stack-empty? 'my-stack)) (pop 'my-stack)) ; pop until empty
(stack-empty? 'my-stack)  → #t ; true

(push 'my-stack 7)
my-stack ; a stack is not a variable, nor a symbol - cannot be evaluated
   ⛔ error: #|user| : unbound variable : my-stack
(stack-top 'my-stack)  → 7


class
	STACK_ON_ARRAY

create
	make

feature -- Implementation

	empty: BOOLEAN
		do
			Result := stack.is_empty
		ensure
			empty: Result = (stack.count = 0)
		end

	push (item: ANY)
		do
			stack.force (item, stack.count)
		ensure
			pushed: stack [stack.upper] = item
			growth: stack.count = old stack.count + 1
		end

	pop: ANY
		require
			not_empty: not empty
		do
			Result := stack.at (stack.upper)
			stack.remove_tail (1)
		ensure
			reduction: stack.count = old stack.count - 1
		end

feature {NONE} -- Initialization

	stack: ARRAY [ANY]

	make
		do
			create stack.make_empty
		end

end


set setglobal local get getlocal return recurse drop dup swap rot over
[] {} pop-from push-to push-through has get-from set-to raise reraise
call for pass


-module( special_variables ).

-export( [task/0] ).

task() -> ok.


Name      Type          Description
---------------------------------------------
TIB      integer    Terminal Input Buffer address
U0       integer    current user area address
>IN      integer    holds offset into TIB, used for parsing
BASE     integer    holds number conversion radix
STATE    integer    holds compiler state (true=compiling, false=interpreting)
DP       integer    holds dictionary memory pointer
'SOURCE  integer[2] contains length and address of input source
LATEST   integer    address of last word added to dictionary
HP       integer    HOLD pointer, used for number formatting routines
LP       integer    leave-stack pointer, used by do loops
S0       integer    end of parameter stack
PAD      chars[80]  Generic buffer. (size is implementation dependent)
L0       integer    bottom of leave stack
R0       integer    end of return stack


           INQUIRE(FILE = FILENAME(1:L),EXIST = EXIST,	!Here we go. Does the file exist?
     1      ERR = 666,IOSTAT = IOSTAT) 		!Hopefully, named in good style, etc.
           IF (EXIST) THEN	!So, does the named file already exist?
           ...etc.


# &keyword # type returned(indicators) - brief description
# indicators:
#    * - generates multiple values
#    = - modifiable
#    ? - may fail (e.g. status inquiry)
#    U - Unicon
#    G - Icon or Unicon with Graphics
#
&allocated   # integer(*) - report memory allocated in total and by storage regions
&ascii       # cset -  ASCII character set
&clock       # string - time of day
&col         # integer(=G) - column location of pointer
&collections # integer(*) - garbage collection activity in total and by storage region
&column      # integer(U) - source code column
&control     # null(?G) - control key state
&cset        # cset - universal character set
&current     # co-expression - current co-expression
&date        # string - today's date
&dateline    # string - time stamp
&digits      # cset - digit characters
&dump        # integer(=) - termination dump
&e           # real - natural log e
&error       # integer(=) - enable/disable error conversion/fail on error
&errno       # integer(?) - variable containing error number from previous posix command
&errornumber # integer(?) - error number of last error converted to failure
&errortext   # string(?) - error message of last error converted to failure
&errorvalue  # any(?) - erroneous value of last error converted to failure
&errout      # file - standard error file
&eventcode   # integer(=U) - program execution event in monitored program
&eventsource # co-expression(=U) - source of events in monitoring program
&eventvalue  # any(=U) - value from event in monitored program
&fail        # none - always fails
&features    # string(*) - identifying features in this version of Icon/Unicon
&file        # string -  current source file
&host        # string - host machine name
&input       # file - standard input file
&interval    # integer(G) - time between input events
&lcase       # cset - lowercase letters
&ldrag       # integer(G) - left button drag
&letters     # cset - letters
&level       # integer - call depth
&line        # integer - current source line number
&lpress      # integer(G) - left button press
&lrelease    # integer(G) - left button release
&main        # co-expression - main task
&mdrag       # integer(G) - middle button drag
&meta        # null(?G) - meta key state
&mpress      # integer(G) - middle button press
&mrelease    # integer(G) - middle button release
&now         # integer(U) - current time
&null        # null - null value
&output      # file - standard output file
&pick        # string (U) - variable containing the result of 3D selection
&phi         # real - golden ratio
&pos         # integer(=) - string scanning position
&progname    # string(=) - program name
&random      # integer(=) - random number seed
&rdrag       # integer(G) - right button drag
&regions     # integer(*) - region sizes
&resize      # integer(G) - window resize
&row         # integer(=G) - row location of pointer
&rpress      # integer(G) - right button press
&rrelease    # integer(G) - right button release
&shift       # null(?G) - shift key state
&source      # co-expression - invoking co-expression
&storage     # integer(*) - memory in use in each region
&subject     # string - string scanning subject
&syserr      # integer - halt on system error
&time        # integer(=) - elapsed time in milliseconds
&trace       # integer(=) - trace program
&ucase       # cset - upper case letters
&version     # string - version
&window      # window(=G) - the current graphics rendering window
&x           # integer(=G) - pointer horizontal position
&y           # integer(=G) - pointer vertical position
# keywords may also fail if the corresponding feature is not present.
# Other variants of Icon (e.g. MT-Icon) will have different mixes of keywords.


void main() {
    import std.stdio;
    enum n = 5;
    int[n][n] M;
    int pos, side = n;

    foreach (immutable i; 0 .. n / 2 + n % 2) {
        foreach (immutable j; 0 .. side)
            M[i][i + j] = pos++;
        foreach (immutable j; 1 .. side)
            M[i + j][n - 1 - i] = pos++;
        foreach_reverse (immutable j; 0 .. side - 1)
            M[n - 1 - i][i + j] = pos++;
        foreach_reverse (immutable j; 1 .. side - 1)
            M[i + j][i] = pos++;
        side -= 2;
    }

    writefln("%(%(%2d %)\n%)", M);
}


public program()
{
    var stack := new system'collections'Stack();

    stack.push:2;

    var isEmpty := stack.Length == 0;

    var item := stack.peek(); // Peek without Popping.

    item := stack.pop()
}


 component GenericStack ( Stack, Element );
 type Stack;
      Stack (MaxSize = integer) -> Stack;
      Empty ( Stack )           -> boolean;
      Full ( Stack )            -> boolean;
      Push ( Stack, Element)    -> nothing;
      Pull ( Stack )            -> Element;
begin
      Stack(MaxSize) =
             Stack:[ MaxSize; index:=0; area=array (Element, MaxSize) ];
      Empty( stack ) = (stack.index <= 0);
      Full ( stack ) = (stack.index >= stack.MaxSize);
      Push ( stack, element ) =
                   [ exception (Full (stack), "Stack Overflow");
                     stack.index:=stack.index + 1;
                     stack.area[stack.index]:=element ];
      Pull ( stack ) =
                   [ exception (Empty (stack), "Stack Underflow");
                     stack.index:=stack.index - 1;
                     stack.area[stack.index + 1] ];
end component GenericStack;


$ p1 = f$integer( p1 )
$ max = p1 * p1
$
$ i = 0
$ r = 1
$ rd = 0
$ c = 1
$ cd = 1
$ loop:
$  a'r'_'c' = i
$  nr = r + rd
$  nc = c + cd
$  if nr .eq. 0 .or. nc .eq. 0 .or. nr .gt. p1 .or. nc .gt. p1 .or. f$type( a'nr'_'nc' ) .nes. ""
$  then
$   gosub change_directions
$  endif
$  r = r + rd
$  c = c + cd
$  i = i + 1
$  if i .lt. max then $ goto loop
$ length = f$length( f$string( max - 1 ))
$ r = 1
$ loop2:
$  c = 1
$  output = ""
$  loop3:
$   output = output + f$fao( "!#UL ", length, a'r'_'c' )
$   c = c + 1
$   if c .le. p1 then $ goto loop3
$  write sys$output output
$  r = r + 1
$  if r .le. p1 then $ goto loop2
$ exit
$
$ change_directions:
$ if rd .eq. 0 .and cd .eq. 1
$ then
$  rd = 1
$  cd = 0
$ else
$  if rd .eq. 1 .and. cd .eq. 0
$  then
$   rd = 0
$   cd = -1
$  else
$   if rd .eq. 0 .and. cd .eq. -1
$   then
$    rd = -1
$    cd = 0
$   else
$    rd = 0
$    cd = 1
$   endif
$  endif
$ endif
$ return


defmodule Stack do
  def new, do: []

  def empty?([]), do: true
  def empty?(_), do: false

  def pop([h|t]), do: {h,t}

  def push(h,t), do: [h|t]

  def top([h|_]), do: h
end


-module(stack).
-export([empty/1, new/0, pop/1, push/2, top/1]).

new() -> [].

empty([]) -> true;
empty(_) -> false.

pop([H|T]) -> {H,T}.

push(H,T) -> [H|T].

top([H|_]) -> H.


BLACK   - The code of colour black.
BLUE    - The code of colour blue.
CYAN    - The code of colour cyan.
DATE$   - The current date in the standard format.
EXLINE  - The number of the last statement that caused an exception.
EXTYPE  - The error code of the last exception.
FREE    - The amount of memory free and avaible to the current program.
GREEN   - The code of colour green.
INF     - The largest positive number that the IS-BASIC can handle.
MAGENTA - The code of colour magenta.
PI      - Value of the Pi. This is rounded to 3.141592654
RED     - The code of colour red.
TIME$   - The current time in the standard format.
WHITE   - The code of colour white.
YELLOW  - The code of colour yellow.
VERNUM  - Version number of the BASIC


  y:  right argument
  x:  (optional) left argument
  u:  left argument to an adverb or conjunction
  v:  right argument to a conjunction
  m:  left noun argument to an adverb or conjunction (value error if verb provided)
  n:  right noun argument to a conjunction (value error if verb provided)


import java.util.Arrays;

public class SpecialVariables {

    public static void main(String[] args) {

        //String-Array args contains the command line parameters passed to the program
        //Note that the "Arrays.toString()"-call is just used for pretty-printing
        System.out.println(Arrays.toString(args));

        //<Classname>.class might qualify as a special variable, since it always contains a Class<T>-object that
        //is used in Reflection
        System.out.println(SpecialVariables.class);

        //The following are not really "variables", since they are properly encapsulated:

        //System.getenv() returns a String-String-Map of environment-variables
        System.out.println(System.getenv());

        //System.getProperties() returns a Map of "things somebody might want to know", including OS and architecture
        // the Java VM runs on, various paths like home direcoty of the user that runs the program, class (library) paths,
        System.out.println(System.getProperties());

        //Runtime.getRuntime() returns a Runtime-Object that contains "changing" data about the running Java VM's
        // environment, like available processor cores or available RAM
        System.out.println(Runtime.getRuntime().availableProcessors());

    }
}


var obj = {
  foo: 1,
  bar: function () { return this.foo; }
};
obj.bar(); // returns 1


$ jq -n -M --arg x 1 '$x|type'   # (*)
"string"


/** Missing scalar multiplication, but we don't need it. */
def makeVector2(x, y) {
  return def vector {
    to x() { return x }
    to y() { return y }
    to add(other) { return makeVector2(x + other.x(), y + other.y()) }
    to clockwise() { return makeVector2(-y, x) }
  }
}

/** Bugs: (1) The printing is specialized. (2) No bounds check on the column. */
def makeFlex2DArray(rows, cols) {
  def storage := ([null] * (rows * cols)).diverge()
  return def flex2DArray {
    to __printOn(out) {
      for y in 0..!rows {
        for x in 0..!cols {
          out.print(<import:java.lang.makeString>.format("%3d", [flex2DArray[y, x]]))
        }
        out.println()
      }
    }
    to get(r, c) { return storage[r * cols + c] }
    to put(r, c, v) { storage[r * cols + c] := v }
  }
}


type Stack<'a> //'//(workaround for syntax highlighting problem)
  (?items) =
  let items = defaultArg items []

  member x.Push(A) = Stack(A::items)

  member x.Pop() =
    match items with
      | x::xr ->  (x, Stack(xr))
      | [] -> failwith "Stack is empty."

  member x.IsEmpty() = items = []

// example usage
let anEmptyStack = Stack<int>()
let stack2 = anEmptyStack.Push(42)
printfn "%A" (stack2.IsEmpty())
let (x, stack3) = stack2.Pop()
printfn "%d" x
printfn "%A" (stack3.IsEmpty())


 V{ 1 2 3 } {
 [ 6 swap push ]
 [ "hi" swap push ]
 [ "Vector is now: " write . ]
 [ "Let's pop it: " write pop . ]
 [ "Vector is now: " write . ]
 [ "Top is: " write last . ] } cleave

 Vector is now: V{ 1 2 3 6 "hi" }
 Let's pop it: "hi"
 Vector is now: V{ 1 2 3 6 }
 Top is: 6


join(sort(filter(sym -> let n=eval(sym); !(isa(n, Function) || isa(n, Type) || isa(n, Module)); end, names(Base))), ", ")


// version 1.0.6

class President(val name: String) {
    var age: Int = 0
        set(value) {
           if (value in 0..125) field = value  // assigning to backing field here
           else throw IllegalArgumentException("$name's age must be between 0 and 125")
        }
}

fun main(args: Array<String>) {
    val pres = President("Donald")
    pres.age = 69
    val pres2 = President("Jimmy")
    pres2.age = 91
    val presidents = mutableListOf(pres, pres2)
    presidents.forEach {
        it.age++  // 'it' is implicit sole parameter of lambda expression
        println("President ${it.name}'s age is currently ${it.age}")
    }
    println()
    val pres3 = President("Theodore")
    pres3.age = 158
}


defmodule RC do
  def spiral_matrix(n) do
    wide = length(to_char_list(n*n-1))
    fmt = String.duplicate("~#{wide}w ", n) <> "~n"
    runs = Enum.flat_map(n..1, &[&1,&1]) |> tl
    delta = Stream.cycle([{0,1},{1,0},{0,-1},{-1,0}])
    running(Enum.zip(runs,delta),0,-1,[])
    |> Enum.with_index |> Enum.sort |>  Enum.chunk(n)
    |> Enum.each(fn row -> :io.format fmt, (for {_,i} <- row, do: i) end)
  end

  defp running([{run,{dx,dy}}|rest], x, y, track) do
    new_track = Enum.reduce(1..run, track, fn i,acc -> [{x+i*dx, y+i*dy} | acc] end)
    running(rest, x+run*dx, y+run*dy, new_track)
  end
  defp running([],_,_,track), do: track |> Enum.reverse
end

RC.spiral_matrix(5)


function spiral(integer dimension)
    integer side, curr, curr2
    sequence s
    s = repeat(repeat(0,dimension),dimension)
    side = dimension
    curr = 0
    for i = 0 to floor(dimension/2) do
        for j = 1 to side-1 do
            s[i+1][i+j] = curr -- top
            curr2 = curr + side-1
            s[i+j][i+side] = curr2 -- right
            curr2 += side-1
            s[i+side][i+side-j+1] = curr2 -- bottom
            curr2 += side-1
            s[i+side-j+1][i+1] = curr2 -- left
            curr += 1
        end for
        curr = curr2 + 1
        side -= 2
    end for

    if remainder(dimension,2) then
        s[floor(dimension/2)+1][floor(dimension/2)+1] = curr
    end if

    return s
end function

? spiral(5)


: stack ( size -- )
  create here cell+ ,  cells allot ;

: push ( n st -- ) tuck @ !  cell swap +! ;
: pop ( st -- n ) -cell over +!  @ @ ;
: empty? ( st -- ? ) dup @ - cell+ 0= ;

10 stack st

1 st push
2 st push
3 st push
st empty? .  \ 0 (false)
st pop . st pop . st pop .  \ 3 2 1
st empty? .  \ -1 (true)


module mod_stack

  implicit none
  type node
    ! data entry in each node
    real*8, private :: data
    ! pointer to the next node of the linked list
    type(node), pointer, private :: next
  end type node
  private node

  type stack
    ! pointer to first element of stack.
    type(node), pointer, private :: first
    ! size of stack
    integer, private :: len=0
  contains
    procedure :: pop
    procedure :: push
    procedure :: peek
    procedure :: getSize
    procedure :: clearStack
    procedure :: isEmpty
  end type stack

contains

  function pop(this) result(x)
    class(stack) :: this
    real*8 :: x
    type(node), pointer :: tmp
    if ( this%len == 0 ) then
      print*, "popping from empty stack"
      !stop
    end if
    tmp => this%first
    x = this%first%data
    this%first => this%first%next
    deallocate(tmp)
    this%len = this%len -1
  end function pop

  subroutine push(this, x)
    real*8 :: x
    class(stack), target :: this
    type(node), pointer :: new, tmp
    allocate(new)
    new%data = x
    if (.not. associated(this%first)) then
      this%first => new
    else
      tmp => this%first
      this%first => new
      this%first%next => tmp
    end if
    this%len = this%len + 1
  end subroutine push

  function peek(this) result(x)
    class(stack) :: this
    real*8 :: x
    x = this%first%data
  end function peek

  function getSize(this) result(n)
    class(stack) :: this
    integer :: n
    n = this%len
  end function getSize

  function isEmpty(this) result(empty)
    class(stack) :: this
    logical :: empty
    if ( this%len > 0 ) then
      empty = .FALSE.
    else
      empty = .TRUE.
    end if
  end function isEmpty

  subroutine clearStack(this)
    class(stack) :: this
    type(node), pointer :: tmp
    integer :: i
    if ( this%len == 0 ) then
      return
    end if
    do i = 1, this%len
      tmp => this%first
      if ( .not. associated(tmp)) exit
      this%first => this%first%next
      deallocate(tmp)
    end do
    this%len = 0
  end subroutine clearStack
end module mod_stack

program main
  use mod_stack
  type(stack) :: my_stack
  integer :: i
  real*8 :: dat
  do i = 1, 5, 1
    dat = 1.0 * i
    call my_stack%push(dat)
  end do
  do while ( .not. my_stack%isEmpty() )
    print*, my_stack%pop()
  end do
  call my_stack%clearStack()
end program main


Module Checkit {
      Let inkey$="hello", dir$="Something Else"
      \\ using a dot we tell to interpreter to skip internal identifiers,
      \\ and look for user variables
      Print .inkey$="hello", .dir$="Something Else"

      Print dir$   ' return current path
      do
            Print "wait to press space"
      Until inkey$=" "
}
Checkit
Module check2 {
      Global inkey$="ok"
      Print .inkey$="ok"
}
check2

Module Check3 {
      Group A {
            Module Check3 {
                  \\ using a dot before the name
                  .inkey$="ok"
                  Print .inkey$="ok"
            }
      }
      A.Check3
}
Check3


Grid[Partition[Names["$*"],4]]
->
$Aborted                       $ActivationGroupID             $ActivationKey                 $ActivationUserRegistered
$AddOnsDirectory               $AllowDataUpdates              $AllowDocumentationUpdates     $AllowInternet
$AssertFunction                $Assumptions                   $BaseDirectory                 $BatchInput
$BatchOutput                   $BoxForms                      $ByteOrdering                  $Canceled
$CharacterEncoding             $CharacterEncodings            $CommandLine                   $CompilationTarget
$ConditionHold                 $ConfiguredKernels             $Context                       $ContextPath
$ControlActiveSetting          $CreationDate                  $CurrentLink                   $DateStringFormat
$DefaultFont                   $DefaultFrontEnd               $DefaultImagingDevice          $DefaultPath
$Display                       $DisplayFunction               $DistributedContexts           $DynamicEvaluation
$Echo                          $Epilog                        $ExportFormats                 $Failed
$FinancialDataSource           $FormatType                    $FrontEnd                      $FrontEndSession
$GeoLocation                   $HistoryLength                 $HomeDirectory                 $IgnoreEOF
$ImagingDevices                $ImportFormats                 $InitialDirectory              $Input
$InputFileName                 $Inspector                     $InstallationDate              $InstallationDirectory
$InstalledServices             $InterfaceEnvironment          $InternetProxyRules            $IterationLimit
$KernelCount                   $KernelID                      $Language                      $LaunchDirectory
$LibraryPath                   $LicenseExpirationDate         $LicenseID                     $LicenseProcesses
$LicenseServer                 $LicenseSubprocesses           $LicenseType                   $Line
$Linked                        $LinkSupported                 $LoadedFiles                   $MachineAddresses
$MachineDomain                 $MachineDomains                $MachineEpsilon                $MachineID
$MachineName                   $MachinePrecision              $MachineType                   $MaxExtraPrecision
$MaxLicenseProcesses           $MaxLicenseSubprocesses        $MaxMachineNumber              $MaxNumber
$MaxPiecewiseCases             $MaxPrecision                  $MaxRootDegree                 $MessageGroups
$MessageList                   $MessagePrePrint               $Messages                      $MinMachineNumber
$MinNumber                     $MinorReleaseNumber            $MinPrecision                  $ModuleNumber
$NetworkLicense                $NewMessage                    $NewSymbol                     $Notebooks
$NumberMarks                   $Off                           $OperatingSystem               $Output
$OutputForms                   $OutputSizeLimit               $Packages                      $PacletSite
$ParentLink                    $ParentProcessID               $PasswordFile                  $PatchLevelID
$Path                          $PathnameSeparator             $PerformanceGoal               $PipeSupported
$Post                          $Pre                           $PreferencesDirectory          $PrePrint
$PreRead                       $PrintForms                    $PrintLiteral                  $PrintServiceRequest
$PrintServiceResponse          $PrintShortErrorMessages       $PrintWSDLDebug                $ProcessID
$ProcessorCount                $ProcessorType                 $ProductInformation            $ProgramName
$RandomState                   $RecursionLimit                $ReleaseNumber                 $RootDirectory
$ScheduledTask                 $ScriptCommandLine             $SessionID                     $SetParentLink
$SharedFunctions               $SharedVariables               $SoundDisplay                  $SoundDisplayFunction
$SuppressInputFormHeads        $SynchronousEvaluation         $SyntaxHandler                 $System
$SystemCharacterEncoding       $SystemID                      $SystemWordLength              $TemporaryDirectory
$TemporaryPrefix               $TextStyle                     $TimedOut                      $TimeUnit
$TimeZone                      $TopDirectory                  $TraceOff                      $TraceOn
$TracePattern                  $TracePostAction               $TracePreAction                $Urgent
$UserAddOnsDirectory           $UserBaseDirectory             $UserBasePacletsDirectory      $UserDocumentsDirectory


/* There are many special variables in Maxima: more than 250 are used for options, for example */
fpprec;  /* precision for big floats */
obase;   /* number base for output */

/* Other variables are read-only, and give the list of user-defined variables, functions... */
infolists; /* give the names of all available lists */
[labels, values, functions, macros, arrays, myoptions, props, aliases, rules, gradefs, dependencies, let_rule_packages, structures]


MCSKIP "WITH" NL
"" Special variables
"" There are four different kinds of variables in ML/I.
"" Permanent (P) variables - these have no special predefined values.
"" Character (C) variables - these have no special predefined values.
"" Temporary (T) variables - a macro has at least three of these, and
""    those have predefined values.
"" System (S) variables - these are for control and status. The number
""    of these is implementation dependent.
MCSKIP MT,<>
MCINS %.
MCDEF TVARDEMO , NL
AS <T-variables are local to the current macro call
T1 is the number of arguments to current macro call - value is %T1.
T2 is the number of macro calls so far - value is %T2.
T3 is the current depth of nesting - value is %T3.
>
TVARDEMO xxx,yyy

MCDEF SVARDEMO WITHS NL
AS <The first nine S-variables are implementation independent
S1 controls startline insertion - value is %S1.
S2 is the current source text line number - value is %S2.
S3 controls error messages related to warning markers - value is %S3.
S4 controls context printout after a <MCNOTE> - value is %S4.
S5 is the count of processing errors - value is %S5.
S6 enables the definition of an atom to be changed - value is %S6.
S7, S8 and S9 are currently unused.

All other S-variables have implementation defined meanings.
>
SVARDEMO


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

class RCSpecialVariables

method RCSpecialVariables()
  x = super.toString
  y = this.toString
  say '<super>'x'</super>'
  say '<this>'y'</this>'
  say '<class>'RCSpecialVariables.class'</class>'
  say '<digits>'digits'</digits>'
  say '<form>'form'</form>'
  say '<[1, 2, 3].length>'
  say [1, 2, 3].length
  say '</[1, 2, 3].length>'
  say '<null>'
  say null
  say '</null>'
  say '<source>'source'</source>'
  say '<sourceline>'sourceline'</sourceline>'
  say '<trace>'trace'</trace>'
  say '<version>'version'</version>'

  say 'Type an answer:'
  say '<ask>'ask'</ask>'

  return

method main(args = String[]) public static

  RCSpecialVariables()

  return


let Spiral n =
    let sq = Array2D.create n n 0                                   // Set up an output array
    let nCur = ref -1                                               // Current value being inserted
    let NextN() = nCur := (!nCur+1) ; !nCur                         // Inc current value and return new value
    let Frame inset =                                               // Create the "frame" at an offset from the outside
        let rangeF = [inset..(n - inset - 2)]                       // Range we use going forward
        let rangeR = [(n - inset - 1)..(-1)..(inset + 1)]           // Range we use going backward
        rangeF |> Seq.iter (fun i -> sq.[inset,i] <- NextN())       // Top of frame
        rangeF |> Seq.iter (fun i -> sq.[i,n-inset-1] <- NextN())   // Right side of frame
        rangeR |> Seq.iter (fun i -> sq.[n-inset-1,i] <- NextN())   // Bottom of frame
        rangeR |> Seq.iter (fun i -> sq.[i,inset] <- NextN())       // Left side of frame
    [0..(n/2 - 1)] |> Seq.iter (fun i -> Frame i)                   // Fill in all frames
    if n &&& 1 = 1 then sq.[n/2,n/2] <- n*n - 1                     // If n is odd, fill in the last single value
    sq                                                              // Return our output array


program Stack;
 {$IFDEF FPC}{$MODE DELPHI}{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}{$ENDIF}
 {$ASSERTIONS ON}
uses Generics.Collections;

var
  lStack: TStack<Integer>;
begin
  lStack := TStack<Integer>.Create;
  try
    lStack.Push(1);
    lStack.Push(2);
    lStack.Push(3);
    Assert(lStack.Peek = 3); // 3 should be at the top of the stack

    Write(lStack.Pop:2);   // 3
    Write(lStack.Pop:2);   // 2
    Writeln(lStack.Pop:2); // 1
    Assert(lStack.Count = 0, 'Stack is not empty'); // should be empty
  finally
    lStack.Free;
  end;
end.


' FB 1.05.0 Win64

' stack_rosetta.bi
' simple generic Stack type

#Define Stack(T) Stack_##T

#Macro Declare_Stack(T)
Type Stack(T)
 Public:
    Declare Constructor()
    Declare Destructor()
    Declare Property capacity As Integer
    Declare Property count As Integer
    Declare Property empty As Boolean
    Declare Property top As T
    Declare Function pop() As T
    Declare Sub push(item As T)
  Private:
    a(any) As T
    count_ As Integer = 0
    Declare Function resize(size As Integer) As Integer
End Type

Constructor Stack(T)()
  Redim a(0 To 0) '' create a default T instance for various purposes
End Constructor

Destructor Stack(T)()
  Erase a
End Destructor

Property Stack(T).capacity As Integer
  Return UBound(a)
End Property

Property Stack(T).count As Integer
  Return count_
End Property

Property Stack(T).empty As Boolean
  Return count_ = 0
End Property

Property Stack(T).top As T
  If count_ > 0 Then
    Return a(count_)
  End If
  Print "Error: Attempted to access 'top' element of an empty stack"
  Return a(0)  '' return default element
End Property

Function Stack(T).pop() As T
  If count_ > 0 Then
    Dim value As T = a(count_)
    a(count_) = a(0)  '' zero element to be removed
    count_ -= 1
    Return value
  End If
  Print "Error: Attempted to remove 'top' element of an empty stack"
  Return a(0)  '' return default element
End Function

Sub Stack(T).push(item As T)
  Dim size As Integer = UBound(a)
  count_ += 1
  If count_ >  size Then
    size = resize(size)
    Redim Preserve a(0 to size)
  End If
  a(count_) = item
End Sub

Function Stack(T).resize(size As Integer) As Integer
  If size = 0 Then
    size = 4
  ElseIf size <= 32 Then
    size  = 2 * size
  Else
    size += 32
  End If
  Return size
End Function

#EndMacro


val argv : string array
(** The command line arguments given to the process.
   The first element is the command name used to invoke the program.
   The following elements are the command-line arguments
   given to the program. *)

val executable_name : string
(** The name of the file containing the executable currently running. *)

val interactive : bool ref
(** This reference is initially set to [false] in standalone
   programs and to [true] if the code is being executed under
   the interactive toplevel system [ocaml]. *)

val os_type : string
(** Operating system currently executing the Caml program. One of
-  ["Unix"] (for all Unix versions, including Linux and Mac OS X),
-  ["Win32"] (for MS-Windows, OCaml compiled with MSVC++ or Mingw),
-  ["Cygwin"] (for MS-Windows, OCaml compiled with Cygwin). *)

val word_size : int
(** Size of one word on the machine currently executing the Caml
   program, in bits: 32 or 64. *)

val max_string_length : int
(** Maximum length of a string. *)

val max_array_length : int
(** Maximum length of a normal array.  The maximum length of a float
    array is [max_array_length/2] on 32-bit machines and
    [max_array_length] on 64-bit machines. *)

val ocaml_version : string
(** [ocaml_version] is the version of Objective Caml.
    It is a string of the form ["major.minor[.patchlevel][+additional-info]"],
    where [major], [minor], and [patchlevel] are integers, and
    [additional-info] is an arbitrary string. The [[.patchlevel]] and
    [[+additional-info]] parts may be absent. *)


USING: arrays grouping io kernel math math.combinatorics
math.ranges math.statistics prettyprint sequences
sequences.repeating ;
IN: rosetta-code.spiral-matrix

: counts ( n -- seq ) 1 [a,b] 2 repeat rest ;

: vals ( n -- seq )
    [ 1 swap 2dup [ neg ] [email protected] 4array ] [ 2 * 1 - cycle ] bi ;

: evJKT2 ( n -- seq )
    [ counts ] [ vals ] bi [ <array> ] 2map concat ;

: spiral ( n -- matrix )
    [ evJKT2 cum-sum inverse-permutation ] [ group ] bi ;

: spiral-demo ( -- ) 5 9 [ spiral simple-table. nl ] [email protected] ;

MAIN: spiral-demo


PROGRAM SPIRAL

  IMPLICIT NONE

  INTEGER, PARAMETER :: size = 5
  INTEGER :: i, x = 0, y = 1, count = size, n = 0
  INTEGER :: array(size,size)

  DO i = 1, count
    x = x + 1
      array(x,y) = n
    n = n + 1
  END DO

  DO
    count = count  - 1
      DO i = 1, count
        y = y + 1
        array(x,y) = n
        n = n + 1
      END DO
      DO i = 1, count
        x = x - 1
        array(x,y) = n
        n = n + 1
      END DO
      IF (n > size*size-1) EXIT
      count = count - 1
      DO i = 1, count
        y = y - 1
        array(x,y) = n
        n = n + 1
      END DO
      DO i = 1, count
        x = x + 1
        array(x,y) = n
        n = n + 1
      END DO
      IF (n > size*size-1) EXIT
  END DO

  DO y = 1, size
    DO x = 1, size
      WRITE (*, "(I4)", ADVANCE="NO") array (x, y)
    END DO
    WRITE (*,*)
  END DO

END PROGRAM SPIRAL


a = new array
a.push[1]
a.push[2]
a.peek[]
while ! a.isEmpty[]
   println[a.pop[]]


[indent=4]
/*
   Stack, in Genie, with GLib double ended Queues
   valac stack.gs
*/
init
    var stack = new Queue of int()

    // push
    stack.push_tail(2)
    stack.push_tail(1)

    // pop (and peek at top)
    print stack.pop_tail().to_string()
    print stack.peek_tail().to_string()

    // empty
    print "stack size before clear: " + stack.get_length().to_string()
    stack.clear()
    print "After clear, stack.is_empty(): " + stack.is_empty().to_string()


true
false
null
System.Out
System.In
System.Err
System.Console
System.Args
Systel.NbCores
System.CELLSIZE
System.VERSION
SYstem.MAXTHREADS
System.ASSERTMODE
System.ISWIN
System.ISLUNIX


program foo(input, output);
begin
	{ In this program, `input` and `output` have special meaning. }
end.


use English;                     # enables use of long variable names

$.     $INPUT_LINE_NUMBER        # sequence number
$,     $OUTPUT_FIELD_SEPARATOR   # output field separator
$;     $SUBSCRIPT_SEPARATOR      # subscript separator for multidimensional array emulation
$_     $ARG                      # topic/current/default variable
$"     $LIST_SEPARATOR           # alternative output field separator
$+     $LAST_PAREN_MATCH         # last substring matched to a regular expression subpattern
$0     $PROGRAM_NAME             # name of the program being executed
$!     $ERRNO                    # error number from host operating system
[email protected]     $EVAL_ERROR               # error from the last "eval" operator
$/     $INPUT_RECORD_SEPARATOR   # input record separator
$\     $OUTPUT_RECORD_SEPARATOR  # output record separator for 'print'
$|     $OUTPUT_AUTOFLUSH         # controls output buffering
$&     $MATCH                    # string matched by last regular expression
$'     $POSTMATCH                # substring following last matched regular expression
$`     $PREMATCH                 # substring preceding last matched regular expression

@ARGV                            # array containing the command line parameters
@F                               # array of fields of each line read in when auto-split is on
@INC                             # array of library search paths

%ENV                             # associative container holding the environment variables
%SIG                             # associative container holding signal handlers


- Global variables start with an asterisk '*'
- Functions and other global symbols start with a lower case letter
- Locally bound symbols start with an upper case letter
- Local functions start with an underscore '_'
- Classes start with a plus-sign '+', where the first letter
   - is in lower case for abstract classes
   - and in upper case for normal classes
- Methods end with a right arrow '>'
- Class variables may be indicated by an upper case letter


Special variables in PL/I are termed "Pseudo-variables".
They are used only on the LHS of an assignment statement.

They include:
   REAL to assign the real part of a COMPLEX variable;
   IMAG to assign the imaginary part of a COMPLEX variable;
   SUBSTR is used to assign part of a string (used on the LHS of an assignment);
   STRING when used on the left-hand of an assignment;
   UNSPEC used to assign a bit pattern to a variable;
   ENTRYADDR is used to assign an address to an ENTRY variable that is
             to be invoked;
   ONCHAR resets the current value of the CHAR built-in function (when
          a data conversion error occurs, and it is desired to re-attempt
          the conversion);
   ONSOURCE assigns a new value to the ONSOURCE built-in function
            (may be used when a data conversion error occurs,
             and a re-try of the conversion is to be attempted with modified data);
   ONGSOURCE assigns a new value to the ONGSOURCE built-in function
            (may be used when a data conversion error occurs,
             and may be used when a re-try of the conversion is to be
             attempted with modified data).


<#
    $$
    $?
    $^
    $_
    $Args
    $ConsoleFileName
    $Error
    $Event
    $EventSubscriber
    $ExecutionContext
    $False
    $ForEach
    $Home
    $Host
    $Input
    $LastExitCode
    $Matches
    $MyInvocation
    $NestedPromptLevel
    $NULL
    $PID
    $Profile
    $PSBoundParameters
    $PsCmdlet
    $PsCulture
    $PSDebugContext
    $PsHome
    $PSitem
    $PSScriptRoot
    $PsUICulture
    $PsVersionTable
    $Pwd
    $Sender
    $ShellID
    $SourceArgs
    $SourceEventArgs
    $This
    $True
#>


names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))
print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )


' FB 1.05.0 Win64

Enum Direction
  across
  down
  back
  up
End Enum

Dim As Integer n

Do
  Input "Enter size of matrix "; n
Loop Until n > 0

Dim spiral(1 To n, 1 To n) As Integer '' all zero by default

' enter the numbers 0 to (n^2 - 1) spirally in the matrix

Dim As Integer row = 1, col = 1, lowRow = 1, highRow = n, lowCol = 1, highCol = n
Dim d As Direction = across

For i As Integer = 0 To (n * n - 1)
  spiral(row, col) = i
  Select Case d
    Case across
      col += 1
      If col > highCol Then
        col = highCol
        row += 1
        d = down
      End if
    Case down
      row += 1
      If row > highRow Then
        row = highRow
        col -= 1
        d = back
      End if
    Case back
      col -= 1
      If col < lowCol Then
        col = lowCol
        row -= 1
        d = up
        lowRow += 1
      End If
    Case up
      row -= 1
      If row < lowRow Then
        row = lowRow
        col += 1
        d = across
        highRow -= 1
        lowCol += 1
        highCol -= 1
      End If
  End Select
Next

' print spiral matrix if n < 20
Print
If n < 20 Then
  For i As Integer = 1 To n
    For j As Integer = 1 To n
      Print Using "####"; spiral(i, j);
    Next j
    Print
  Next i
Else
  Print "Matrix is too big to display on 80 column console"
End If

Print
Print "Press any key to quit"
Sleep


def stack = []
assert stack.empty

stack.push(55)
stack.push(21)
stack.push('kittens')
assert stack.last() == 'kittens'
assert stack.size() == 3
assert ! stack.empty

println stack

assert stack.pop() == "kittens"
assert stack.size() == 2

println stack

stack.push(-20)

println stack

stack.push( stack.pop() * stack.pop() )
assert stack.last() == -420
assert stack.size() == 2

println stack

stack.push(stack.pop() / stack.pop())
assert stack.size() == 1

println stack

println stack.pop()
assert stack.size() == 0
assert stack.empty

try { stack.pop() } catch (NoSuchElementException e) { println e.message }


 $foo   scalar (object)
 @foo   ordered array
 %foo   unordered hash (associative array)
 &foo   code/rule/token/regex
 ::foo  package/module/class/role/subset/enum/type/grammar


/*REXX program demonstrates REXX special variables:  RC,  RESULT,  SIGL */
                           /*line two.  */
                           /*line three.*/             say copies('═',79)
rc=1/3                     /*line four. */
signal youWho              /*line five. */
myLoo='this got skipped'   /*line six.  */
youwho:                    /*line seven.*/
sep=copies('─', 9)         /*line eight.*/
say sep  'SIGL=' sigl      /*line nine. */
say sep  'REXX source statement' SIGL '=' sourceline(sigl)
                                                       say copies('═',79)
g=44
call halve  g
say sep  'rc='     rc
say sep  'result=' result
                                                       say copies('═',79)
h=66
hh=halve(h)
say sep  'rc='     rc
say sep  'result=' result
say sep  'hh='     hh
                                                       say copies('═',79)
'DIR  /ad  /b'                         /*display the directories (Bare).*/
say sep  'rc='     rc
say sep  'result=' result
                                                       say copies('═',79)
exit                                   /*stick a fork in it, we're done.*/
/*──────────────────────────────────HALVE subroutine────────────────────*/
halve: return arg(1) / 2               /*a simple halving function.     */


# Spiral matrix with numbers 1 .. n2, more natural in GAP
SpiralMatrix := function(n)
  local i, j, k, di, dj, p, vi, vj, imin, imax, jmin, jmax;
  a := NullMat(n, n);
  vi := [ 1, 0, -1, 0 ];
  vj := [ 0, 1, 0, -1 ];
  imin := 0;
  imax := n;
  jmin := 1;
  jmax := n + 1;
  p := 1;
  di := vi[p];
  dj := vj[p];
  i := 1;
  j := 1;
  for k in [1 .. n*n] do
    a[j][i] := k;
    i := i + di;
    j := j + dj;
    if i < imin or i > imax or j < jmin or j > jmax then
      i := i - di;
      j := j - dj;
      p := RemInt(p, 4) + 1;
      di := vi[p];
      dj := vj[p];
      i := i + di;
      j := j + dj;
      if p = 1 then
        imax := imax - 1;
      elif p = 2 then
        jmax := jmax - 1;
      elif p = 3 then
        imin := imin + 1;
      else
        jmin := jmin + 1;
      fi;
    fi;
  od;
  return a;
end;

PrintArray(SpiralMatrix(5));
# [ [   1,   2,   3,   4,   5 ],
#   [  16,  17,  18,  19,   6 ],
#   [  15,  24,  25,  20,   7 ],
#   [  14,  23,  22,  21,   8 ],
#   [  13,  12,  11,  10,   9 ] ]


package main

import (
    "fmt"
    "strconv"
)

var n = 5

func main() {
    if n < 1 {
        return
    }
    top, left, bottom, right := 0, 0, n-1, n-1
    sz := n * n
    a := make([]int, sz)
    i := 0
    for left < right {
        // work right, along top
        for c := left; c <= right; c++ {
            a[top*n+c] = i
            i++
        }
        top++
        // work down right side
        for r := top; r <= bottom; r++ {
            a[r*n+right] = i
            i++
        }
        right--
        if top == bottom {
            break
        }
        // work left, along bottom
        for c := right; c >= left; c-- {
            a[bottom*n+c] = i
            i++
        }
        bottom--
        // work up left side
        for r := bottom; r >= top; r-- {
            a[r*n+left] = i
            i++
        }
        left++
    }
    // center (last) element
    a[top*n+left] = i

    // print
    w := len(strconv.Itoa(n*n - 1))
    for i, e := range a {
        fmt.Printf("%*d ", w, e)
        if i%n == n-1 {
            fmt.Println("")
        }
    }
}


type Stack a = [a]

create :: Stack a
create = []

push :: a -> Stack a -> Stack a
push = (:)

pop :: Stack a -> (a, Stack a)
pop []     = error "Stack empty"
pop (x:xs) = (x,xs)

empty :: Stack a -> Bool
empty = null

peek :: Stack a -> a
peek []    = error "Stack empty"
peek (x:_) = x


procedure main()
stack := []                                     # new empty stack
push(stack,1)                                   # add item
push(stack,"hello",table(),set(),[],5)          # add more items of mixed types in order left to right
y := top(stack)                                 # peek
x := pop(stack)                                 # remove item
write("The stack is ",if isempty(stack) then "empty" else "not empty")
end

procedure isempty(x)           #: test if a datum is empty, return the datum or fail (task requirement)
if *x = 0 then return x        #  in practice just write *x = 0 or *x ~= 0 for is/isn't empty
end

procedure top(x)               #: return top element w/o changing stack
return x[1]                    #  in practice, just use x[1]
end


import scala._    // Wild card -- all of scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]]       // Higher kinded type parameter
def f(m: M[_])    // Existential type
_ + _             // Anonymous function placeholder parameter
m _               // Eta expansion of method into method value
m(_)              // Partial function application
_ => 5            // Discarded parameter
case _ =>         // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10)  // same thing
f(xs: _*)         // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _    // Initialization to the default value
def abc_<>!       // An underscore must separate alphanumerics from symbols on identifiers
t._2              // Part of a method name, such as tuple getters
var i: Int = _    // Initialization with a default value
for (_ <- 1 to 10) doIt() // Discarded val
def f: T; def f_=(t: T) // Combo for creating mutable f member.


# contains arguments passed to the ursa
# interpreter on the command line
string<> args

# iodevice that points to the console by default
iodevice console

# contains "\n"
string endl

# represents false
boolean false

# represents true
boolean true


*PACKAGE*
*READTABLE*
*ERROR-HANDLER*
*UNBOUND-HANDLER*
*LOAD-PATH*
*STANDARD-INPUT*
*STANDARD-OUTPUT*
*ERROR-OUTPUT*
*FIXNUM-FORMAT*
*HEXNUM-FORMAT*
*FLONUM-FORMAT*
*PRINT-CASE*
*SOFTWARE-TYPE*
T                ; bound to #T
NIL              ; bound to '()
OBJECT
CLASS


class Parent {
    construct new(name) {
        _name = name
    }

    name { _name }
}

class Child is Parent {
    construct new(name, parentName) {
        _name = name
        super(parentName)  // call parent's constructor
    }

    name { _name } // overrides Parent's name method

    printNames() {
        System.print("My name is %(this.name) and my parent's name is %(super.name).")
    }
}

var c = Child.new("John", "Fred")
c.printNames()


enum Direction {
    East([0,1]), South([1,0]), West([0,-1]), North([-1,0]);
    private static _n
    private final stepDelta
    private bound

    private Direction(delta) {
        stepDelta = delta
    }

    public static setN(int n) {
        Direction._n = n
        North.bound = 0
        South.bound = n-1
        West.bound = 0
        East.bound = n-1
    }

    public List move(i, j) {
        def dir = this
        def newIJDir = [[i,j],stepDelta].transpose().collect { it.sum() } + dir
        if (((North.bound)..(South.bound)).contains(newIJDir[0])
            && ((West.bound)..(East.bound)).contains(newIJDir[1])) {
            newIJDir
        } else {
            (++dir).move(i, j)
        }
    }

    public Object next() {
        switch (this) {
            case North: West.bound++; return East;
            case East: North.bound++; return South;
            case South: East.bound--; return West;
            case West: South.bound--; return North;
        }
    }
}

def spiralMatrix = { n ->
    if (n < 1) return []
    def M = (0..<n).collect { [0]*n }
    def i = 0
    def j = 0
    Direction.n = n
    def dir = Direction.East
    (0..<(n**2)).each { k ->
        M[i][j] = k
        (i,j,dir) = (k < (n**2 - 1)) \
            ? dir.move(i,j) \
            : [i,j,dir]
    }
    M
}


Node := Object clone do(
    next := nil
    obj := nil
)

Stack := Object clone do(
    node := nil

    pop := method(
        obj := node obj
        node = node next
        obj
    )

    push := method(obj,
        nn := Node clone
        nn obj = obj
        nn next = self node
        self node = nn
    )
)


Stack = Origin mimic do(
  initialize = method(@elements = [])
  pop = method(@elements pop!)
  empty = method(@elements empty?)
  push = method(element, @elements push!(element))
)


org &0066

NMI_HANDLER:   ;this label is optional, the CPU doesn't need it to know how to jump here.
retn           ;in this example, the NMI routine will immediately return without doing anything.


10 PRINT "The border colour is "; PEEK (23624): REM bordcr
20 PRINT "The ramtop address is "; PEEK (23730) + 256 * PEEK (23731): REM ramtop
30 POKE 23609,50: REM set keyboard pip to 50


import Data.List
import Control.Monad
grade xs = map snd. sort $ zip xs [0..]
values n = cycle [1,n,-1,-n]
counts n = (n:).concatMap (ap (:) return)  $ [n-1,n-2..1]
reshape n = unfoldr (\xs -> if null xs then Nothing else Just (splitAt n xs))
spiral n = reshape n . grade. scanl1 (+). concat $ zipWith replicate (counts n) (values n)
displayRow = putStrLn . intercalate " " . map show
main = mapM displayRow $ spiral 5


100 LET N=255 ! Size of stack
110 NUMERIC STACK(1 TO N)
120 LET PTR=1
130 DEF PUSH(X)
140   IF PTR>N THEN
150     PRINT "Stack is full.":STOP
160   ELSE
170     LET STACK(PTR)=X:LET PTR=PTR+1
180   END IF
190 END DEF
200 DEF POP
210   IF PTR=1 THEN
220     PRINT "Stack is empty.":STOP
230   ELSE
240     LET PTR=PTR-1:LET POP=STACK(PTR)
250   END IF
260 END DEF
270 DEF EMPTY
280   LET PTR=1
290 END DEF
300 DEF TOP=STACK(PTR-1)
310 CALL PUSH(3):CALL PUSH(5)
320 PRINT POP+POP


stack=: ''
push=: monad def '0$stack=:stack,y'
pop=: monad def 'r[ stack=:}:stack[ r=.{:stack'
empty=: monad def '0=#stack'


import java.util.Stack;

public class StackTest {
    public static void main( final String[] args ) {
        final Stack<String> stack = new Stack<String>();

        System.out.println( "New stack empty? " + stack.empty() );

        stack.push( "There can be only one" );
        System.out.println( "Pushed stack empty? " + stack.empty() );
        System.out.println( "Popped single entry: " + stack.pop() );

        stack.push( "First" );
        stack.push( "Second" );
        System.out.println( "Popped entry should be second: " + stack.pop() );

        // Popping an empty stack will throw...
        stack.pop();
        stack.pop();
    }
}


procedure main(A)        # spiral matrix
N := 0 < integer(\A[1]|5)           # N=1... (dfeault 5)
WriteMatrix(SpiralMatrix(N))
end

procedure WriteMatrix(M)             #: write the matrix
every x := M[r := 1 to *M, c := 1 to *M[r]] do
   writes(right(\x|"-", 3), if c = *M[r] then "\n" else "")
return
end

procedure SpiralMatrix(N)            #: create spiral matrix
every (!(M := list(N))):= list(N)    # build empty matrix NxN
                                     # setup before starting first turn
corner := 0                          # . corner we're at
i := -1                              # . cell contents
r:= 1 ; c :=0                        # . row & col
cincr := integer(sin(0))             # . column incr

until i > N^2 do {
   rincr := cincr                              # row incr follows col
   cincr := integer(sin(&pi/2*(corner+:=1)))   # col incr at each corner
   if (run := N-corner/2)  = 0 then break      # shorten run to 0 at U/R & L/L
   every run to 1 by -1 do
      M[r +:= rincr,c +:= cincr] := i +:= 1    # move, count, and fill
   }
return M
end


var stack = [];
stack.push(1)
stack.push(2,3);
print(stack.pop());   // 3
print(stack.length);   // 2, stack empty if 0