import java.math.BigInteger;
import java.util.Arrays;

public class CircularPrimes {
    public static void main(String[] args) {
        System.out.println("First 19 circular primes:");
        int p = 2;
        for (int count = 0; count < 19; ++p) {
            if (isCircularPrime(p)) {
                if (count > 0)
                    System.out.print(", ");
                System.out.print(p);
                ++count;
            }
        }
        System.out.println();
        System.out.println("Next 4 circular primes:");
        int repunit = 1, digits = 1;
        for (; repunit < p; ++digits)
            repunit = 10 * repunit + 1;
        BigInteger bignum = BigInteger.valueOf(repunit);
        for (int count = 0; count < 4; ) {
            if (bignum.isProbablePrime(15)) {
                if (count > 0)
                    System.out.print(", ");
                System.out.printf("R(%d)", digits);
                ++count;
            }
            ++digits;
            bignum = bignum.multiply(BigInteger.TEN);
            bignum = bignum.add(BigInteger.ONE);
        }
        System.out.println();
        testRepunit(5003);
        testRepunit(9887);
        testRepunit(15073);
        testRepunit(25031);
    }

    private static boolean isPrime(int n) {
        if (n < 2)
            return false;
        if (n % 2 == 0)
            return n == 2;
        if (n % 3 == 0)
            return n == 3;
        for (int p = 5; p * p <= n; p += 4) {
            if (n % p == 0)
                return false;
            p += 2;
            if (n % p == 0)
                return false;
        }
        return true;
    }

    private static int cycle(int n) {
        int m = n, p = 1;
        while (m >= 10) {
            p *= 10;
            m /= 10;
        }
        return m + 10 * (n % p);
    }

    private static boolean isCircularPrime(int p) {
        if (!isPrime(p))
            return false;
        int p2 = cycle(p);
        while (p2 != p) {
            if (p2 < p || !isPrime(p2))
                return false;
            p2 = cycle(p2);
        }
        return true;
    }

    private static void testRepunit(int digits) {
        BigInteger repunit = repunit(digits);
        if (repunit.isProbablePrime(15))
            System.out.printf("R(%d) is probably prime.\n", digits);
        else
            System.out.printf("R(%d) is not prime.\n", digits);
    }

    private static BigInteger repunit(int digits) {
        char[] ch = new char[digits];
        Arrays.fill(ch, '1');
        return new BigInteger(new String(ch));
    }
}


type MyClass = object
  name: int

proc initMyClass(): MyClass =
  result.name = 2

proc someMethod(m: var MyClass) =
  m.name = 1

var mc = initMyClass()
mc.someMethod()

type
  Gender = enum male, female, other

  MyOtherClass = object
    name: string
    gender: Gender
    age: Natural

proc initMyOtherClass(name; gender = female; age = 50): auto =
  MyOtherClass(name: name, gender: gender, age: age)

var person1 = initMyOtherClass("Jane")
echo person1.name, " ", person1.gender, " ", person1.age # Jane female 50
var person2 = initMyOtherClass("John", male, 23)
echo person2.name, " ", person2.gender, " ", person2.age # John male 23


MODULE M;

   TYPE
      T = POINTER TO TDesc;
      TDesc = RECORD
         x: INTEGER
      END;

   PROCEDURE New*(): T;
      VAR t: T;
   BEGIN
      NEW(t); t.x := 0;
      RETURN t
   END New;

   PROCEDURE (t: T) Increment*;
   BEGIN
      INC(t.x)
   END Increment;

END M.


bundle Default {
  class MyClass {
    @var : Int;

    New() {
    }

    method : public : SomeMethod() ~ Nil {
    	@var := 1;
    }

    method : public : SetVar(var : Int) ~ Nil {
      @var := var;
    }

    method : public : GetVar() ~ Int {
      return @var;
    }
  }

  class Test {
    function : Main(args : String[]) ~ Nil {
      inst := MyClass->New();
      inst->GetVar()->PrintLine();

      inst->SomeMethod();
      inst->GetVar()->PrintLine();

      inst->SetVar(15);
      inst->GetVar()->PrintLine();
    }
  }
}


def is_circular_prime:
    def circle: range(0;length) as $i | .[$i:] + .[:$i];
    tostring as $s
    | [$s|circle|tonumber] as $c
    | . == ($c|min) and all($c|unique[]; is_prime);

def circular_primes:
   2, (range(3; infinite; 2) | select(is_circular_prime));

# Probably only useful with unbounded-precision integer arithmetic:
def repunits:
  1 | recurse(10*. + 1);


using Lazy, Primes

function iscircularprime(n)
    !isprime(n) && return false
    dig = digits(n)
    return all(i -> (m = evalpoly(10, circshift(dig, i))) >= n && isprime(m), 1:length(dig)-1)
end

filtcircular(n, rang) = Int.(collect(take(n, filter(iscircularprime, rang))))
isprimerepunit(n) = isprime(evalpoly(BigInt(10), ones(Int, n)))
filtrep(n, rang) = collect(take(n, filter(isprimerepunit, rang)))

println("The first 19 circular primes are:\n", filtcircular(19, Lazy.range(2)))
print("\nThe next 4 circular primes, in repunit format, are: ",
    mapreduce(n -> "R($n) ", *, filtrep(4, Lazy.range(6))))

println("\n\nChecking larger repunits:")
for i in [5003, 9887, 15073, 25031, 35317, 49081]
    println("R($i) is ", isprimerepunit(i) ? "prime." : "not prime.")
end


USING: combinators continuations formatting grouping io kernel
literals math.order math.text.utils multiline sequences
splitting ;

CONSTANT: numerals $[
HEREDOC: END
  +    +-+  +    +    + +  +-+  + +  +-+  + +  +-+
  |    |    |    |\   |/   |/   | |  | |  | |  | |
  |    |    +-+  | +  +    +    | +  | +  +-+  +-+
  |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |
  +    +    +    +    +    +    +    +    +    +
END
"\n" split harvest [ 5 group ] map flip
]

: precedence ( char char -- char )
    2dup [ CHAR: + = ] either? [ 2drop CHAR: + ] [ max ] if ;

: overwrite ( glyph glyph -- newglyph )
    [ [ precedence ] 2map ] 2map ;

: flip-slashes ( str -- new-str )
    [
        {
            { CHAR: / [ CHAR: \ ] }
            { CHAR: \ [ CHAR: / ] }
            [ ]
        } case
    ] map ;

: hflip ( seq -- newseq ) [ reverse flip-slashes ] map ;
: vflip ( seq -- newseq ) reverse [ flip-slashes ] map ;

: get-digits ( n -- seq ) 1 digit-groups 4 0 pad-tail ;

: check-cistercian ( n -- )
    0 9999 between? [ "Must be from 0 to 9999." throw ] unless ;

: .cistercian ( n -- )
    [ check-cistercian ] [ "%d:\n" printf ] [ get-digits ] tri
    [ numerals nth ] map
    [ { [ ] [ hflip ] [ vflip ] [ hflip vflip ] } spread ]
    with-datastack [ ] [ overwrite ] map-reduce [ print ] each ;

{ 0 1 20 300 4000 5555 6789 8015 } [ .cistercian nl ] each


type
 MyClass = object
            variable: integer;
            constructor init;
            destructor done;
            procedure someMethod;
           end;

constructor MyClass.init;
 begin
  variable := 0;
 end;

procedure MyClass.someMethod;
 begin
  variable := 1;
 end;

var
 instance: MyClass; { as variable }
 pInstance: ^MyClass; { on free store }

begin
 { create instances }
 instance.init;
 new(pInstance, init); { alternatively: pInstance := new(MyClass, init); }

 { call method }
 instance.someMethod;
 pInstance^.someMethod;

 { get rid of the objects }
 instance.done;
 dispose(pInstance, done);
end;


// There are no class variables, so static variables are used.
static int myClassVariable = 0;

@interface MyClass : NSObject
{
    int variable; // instance variable
}

- (int)variable; // Typical accessor - you should use the same name as the variable

@end


-- Circular primes, in Lua, 6/22/2020 db
local function isprime(n)
  if n < 2 then return false end
  if n % 2 == 0 then return n==2 end
  if n % 3 == 0 then return n==3 end
  for f = 5, math.sqrt(n), 6 do
    if n % f == 0 or n % (f+2) == 0 then return false end
  end
  return true
end

local function iscircularprime(p)
  local n = math.floor(math.log10(p))
  local m, q = 10^n, p
  for i = 0, n do
    if (q < p or not isprime(q)) then return false end
    q = (q % m) * 10 + math.floor(q / m)
  end
  return true
end

local p, dp, list, N = 2, 1, {}, 19
while #list < N do
  if iscircularprime(p) then list[#list+1] = p end
  p, dp = p + dp, 2
end
print(table.concat(list, ", "))


ClearAll[RepUnit, CircularPrimeQ]
RepUnit[n_] := (10^n - 1)/9
CircularPrimeQ[n_Integer] := Module[{id = IntegerDigits[n], nums, t},
  AllTrue[
   Range[Length[id]]
   ,
   Function[{z},
    t = FromDigits[RotateLeft[id, z]];
    If[t < n,
     False
     ,
     PrimeQ[t]
     ]
    ]
   ]
  ]
Select[Range[200000], CircularPrimeQ]

res = {};
Dynamic[res]
Do[
 If[CircularPrimeQ[RepUnit[n]], AppendTo[res, n]]
 ,
 {n, 1000}
 ]

Scan[[email protected]*[email protected]*RepUnit, {5003, 9887, 15073, 25031, 35317, 49081}]


class my_class =
  object (self)
    val mutable variable = 0
    method some_method = variable <- 1
  end


Object Class new: MyClass(att)
MyClass method: initialize(v)  v := att ;


p = .point~new
c = .circle~new

p~print
c~print

::class point
::method init
  expose x y
  use strict arg x = 0, y = 0   -- defaults to 0 for any non-specified coordinates

::attribute x
::attribute y

::method print
  expose x y
  say "A point at location ("||x","y")"

::class circle subclass point
::method init
  expose radius
  use strict arg x = 0, y = 0, radius = 0
  self~init:super(x, y)        -- call superclass constructor

::attribute radius

::method print
  expose radius
  say "A circle of radius" radius "centered at location ("||self~x","self~y")"


program CircularPrimes;
//nearly the way it is done:
//http://www.worldofnumbers.com/circular.htm
//base 4 counter to create numbers with first digit is the samallest used.
//check if numbers are tested before and reduce gmp-calls by checking with prime 3,7

{$IFDEF FPC}
  {$MODE DELPHI}{$OPTIMIZATION ON,ALL}
  uses
    Sysutils,gmp;
{$ENDIF}
{$IFDEF Delphi}
  uses
    System.Sysutils,?gmp?;
{$ENDIF}

{$IFDEF WINDOWS}
   {$APPTYPE CONSOLE}
{$ENDIF}
const
  MAXCNTOFDIGITS = 14;
  MAXDGTVAL = 3;
  conv : array[0..MAXDGTVAL+1] of byte = (9,7,3,1,0);
type
  tDigits = array[0..23] of byte;
  tUint64 = NativeUint;
var
  mpz : mpz_t;
  digits,
  revDigits : tDigits;
  CheckNum : array[0..19] of tUint64;
  Found : array[0..23] of tUint64;
  Pot_ten,Count,CountNumCyc,CountNumPrmTst : tUint64;

procedure CheckOne(MaxIdx:integer);
var
  Num : Uint64;
  i : integer;
begin
  i:= MaxIdx;
  repeat
    inc(CountNumPrmTst);
    num := CheckNum[i];
    mpz_set_ui(mpz,Num);
    If mpz_probab_prime_p(mpz,3)=0then
      EXIT;
    dec(i);
  until i < 0;
  Found[Count] := CheckNum[0];
  inc(count);
end;

function CycleNum(MaxIdx:integer):Boolean;
//first create circular numbers to minimize prime checks
var
  cycNum,First,P10 : tUint64;
  i,j,cv : integer;
Begin
  i:= MaxIdx;
  j := 0;
  First := 0;
  repeat
    cv := conv[digits[i]];
    dec(i);
    First := First*10+cv;
    revDigits[j]:= cv;
    inc(j);
  until i < 0;
  // if num is divisible by 3 then cycle numbers also divisible by 3 same sum of digits
  IF First MOD 3 = 0 then
    EXIT(false);
  If First mod 7 = 0 then
     EXIT(false);

  //if one of the cycled number must have been tested before break
  P10 := Pot_ten;
  i := 0;
  j := 0;
  CheckNum[j] := First;
  cycNum := First;
  repeat
    inc(CountNumCyc);
    cv := revDigits[i];
    inc(j);
    cycNum := (cycNum - cv*P10)*10+cv;
    //num was checked before
    if cycNum < First then
      EXIT(false);
    if cycNum mod 7 = 0 then
      EXIT(false);
    CheckNum[j] := cycNum;
    inc(i);
  until i >= MaxIdx;
  EXIT(true);
end;

var
  T0: Int64;

  idx,MaxIDx,dgt,MinDgt : NativeInt;
begin
  T0 := GetTickCount64;
  mpz_init(mpz);

  fillchar(digits,Sizeof(digits),chr(MAXDGTVAL));
  Count :=0;
  For maxIdx := 2 to 10 do
    if maxidx in[2,3,5,7] then
    begin
      Found[Count]:= maxIdx;
      inc(count);
    end;

  Pot_ten := 10;
  maxIdx := 1;
  idx := 0;
  MinDgt := MAXDGTVAL;
  repeat
    if CycleNum(MaxIdx) then
        CheckOne(MaxIdx);
    idx := 0;
    repeat
      dgt := digits[idx]-1;
      if dgt >=0 then
        break;
      digits[idx] := MinDgt;
      inc(idx);
    until idx >MAXCNTOFDIGITS-1;

    if idx > MAXCNTOFDIGITS-1 then
      BREAK;

    if idx<=MaxIDX then
    begin
      digits[idx] := dgt;
      //change all to leading digit
      if idx=MaxIDX then
      Begin
        For MinDgt := 0 to idx do
          digits[MinDgt]:= dgt;
        minDgt := dgt;
      end;
    end
    else
    begin
      minDgt := MAXDGTVAL;
      For maxidx := 0 to idx do
        digits[MaxIdx] := MAXDGTVAL;
      Maxidx := idx;
      Pot_ten := Pot_ten*10;
      writeln(idx:7,count:7,CountNumCyc:16,CountNumPrmTst:12,GetTickCount64-T0:8);
    end;
  until false;
  writeln(idx:7,count:7,CountNumCyc:16,CountNumPrmTst:12,GetTickCount64-T0:8);
  T0 := GetTickCount64-T0;

  For idx := 0 to count-2 do
    write(Found[idx],',');
  writeln(Found[count-1]);

  writeln('It took ',T0,' ms ','to check ',MAXCNTOFDIGITS,' decimals');
  mpz_clear(mpz);
  {$IFDEF WINDOWS}
   readln;
  {$ENDIF}
end.


   main'jc.svg'[load'jc.ijs'
open browser to /tmp/jc.svg


import java.util.Arrays;
import java.util.List;

public class Cistercian {
    private static final int SIZE = 15;
    private final char[][] canvas = new char[SIZE][SIZE];

    public Cistercian(int n) {
        initN();
        draw(n);
    }

    public void initN() {
        for (var row : canvas) {
            Arrays.fill(row, ' ');
            row[5] = 'x';
        }
    }

    private void horizontal(int c1, int c2, int r) {
        for (int c = c1; c <= c2; c++) {
            canvas[r][c] = 'x';
        }
    }

    private void vertical(int r1, int r2, int c) {
        for (int r = r1; r <= r2; r++) {
            canvas[r][c] = 'x';
        }
    }

    private void diagd(int c1, int c2, int r) {
        for (int c = c1; c <= c2; c++) {
            canvas[r + c - c1][c] = 'x';
        }
    }

    private void diagu(int c1, int c2, int r) {
        for (int c = c1; c <= c2; c++) {
            canvas[r - c + c1][c] = 'x';
        }
    }

    private void draw(int v) {
        var thousands = v / 1000;
        v %= 1000;

        var hundreds = v / 100;
        v %= 100;

        var tens = v / 10;
        var ones = v % 10;

        drawPart(1000 * thousands);
        drawPart(100 * hundreds);
        drawPart(10 * tens);
        drawPart(ones);
    }

    private void drawPart(int v) {
        switch (v) {
            case 1:
                horizontal(6, 10, 0);
                break;
            case 2:
                horizontal(6, 10, 4);
                break;
            case 3:
                diagd(6, 10, 0);
                break;
            case 4:
                diagu(6, 10, 4);
                break;
            case 5:
                drawPart(1);
                drawPart(4);
                break;
            case 6:
                vertical(0, 4, 10);
                break;
            case 7:
                drawPart(1);
                drawPart(6);
                break;
            case 8:
                drawPart(2);
                drawPart(6);
                break;
            case 9:
                drawPart(1);
                drawPart(8);
                break;

            case 10:
                horizontal(0, 4, 0);
                break;
            case 20:
                horizontal(0, 4, 4);
                break;
            case 30:
                diagu(0, 4, 4);
                break;
            case 40:
                diagd(0, 4, 0);
                break;
            case 50:
                drawPart(10);
                drawPart(40);
                break;
            case 60:
                vertical(0, 4, 0);
                break;
            case 70:
                drawPart(10);
                drawPart(60);
                break;
            case 80:
                drawPart(20);
                drawPart(60);
                break;
            case 90:
                drawPart(10);
                drawPart(80);
                break;

            case 100:
                horizontal(6, 10, 14);
                break;
            case 200:
                horizontal(6, 10, 10);
                break;
            case 300:
                diagu(6, 10, 14);
                break;
            case 400:
                diagd(6, 10, 10);
                break;
            case 500:
                drawPart(100);
                drawPart(400);
                break;
            case 600:
                vertical(10, 14, 10);
                break;
            case 700:
                drawPart(100);
                drawPart(600);
                break;
            case 800:
                drawPart(200);
                drawPart(600);
                break;
            case 900:
                drawPart(100);
                drawPart(800);
                break;

            case 1000:
                horizontal(0, 4, 14);
                break;
            case 2000:
                horizontal(0, 4, 10);
                break;
            case 3000:
                diagd(0, 4, 10);
                break;
            case 4000:
                diagu(0, 4, 14);
                break;
            case 5000:
                drawPart(1000);
                drawPart(4000);
                break;
            case 6000:
                vertical(10, 14, 0);
                break;
            case 7000:
                drawPart(1000);
                drawPart(6000);
                break;
            case 8000:
                drawPart(2000);
                drawPart(6000);
                break;
            case 9000:
                drawPart(1000);
                drawPart(8000);
                break;

        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        for (var row : canvas) {
            builder.append(row);
            builder.append('\n');
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {
            System.out.printf("%d:\n", number);
            var c = new Cistercian(number);
            System.out.println(c);
        }
    }
}


Class MyObject

static int count 'statics are private

int a,b,c
bstring s

method constructor(int pa,pb,pc)
  s="constructed"
  a=pa : b=pb : c=pc
  count++
end method

method destructor()
  del s
end method

method sum() as int
  return a+b+c
end method

end class

new MyObject v(2,4,6)

print "Sum: " v.sum

del v


use strict;
use warnings;
use feature 'say';
use List::Util 'min';
use ntheory 'is_prime';

sub rotate { my($i,@a) = @_; join '', @a[$i .. @a-1, 0 .. $i-1] }

sub isCircular {
    my ($n) = @_;
    return 0 unless is_prime($n);
    my @circular = split //, $n;
    return 0 if min(@circular) < $circular[0];
    for (1 .. scalar @circular) {
        my $r = join '', rotate($_,@circular);
        return 0 unless is_prime($r) and $r >= $n;
    }
    1
}

say "The first 19 circular primes are:";
for ( my $i = 1, my $count = 0; $count < 19; $i++ ) {
    ++$count and print "$i " if isCircular($i);
}

say "\n\nThe next 4 circular primes, in repunit format, are:";
for ( my $i = 7, my $count = 0; $count < 4; $i++ ) {
    ++$count and say "R($i)" if is_prime 1 x $i
}

say "\nRepunit testing:";

for (5003, 9887, 15073, 25031, 35317, 49081) {
    say "R($_): Prime? " . (is_prime 1 x $_ ? 'True' : 'False');
}


// html
document.write(`

<input id="num" type="number" min="0" max="9999" value="0" onchange="showCist()">

<canvas id="cist" width="200" height="300"></canvas>

    <button onclick="set(0)">0</button>
    <button onclick="set(1)">1</button>
    <button onclick="set(20)">20</button>
    <button onclick="set(300)">300</button>
    <button onclick="set(4000)">4000</button>
    <button onclick="set(5555)">5555</button>
    <button onclick="set(6789)">6789</button>
    <button onclick="set(Math.floor(Math.random()*1e4))">Random</button>

`);

// to show given examples
// can be deleted for normal use
function set(num) {
  document.getElementById('num').value = num;
  showCist();
}

const SW = 10; // stroke width
let canvas = document.getElementById('cist'),
    cx = canvas.getContext('2d');

function showCist() {
  // reset canvas
  cx.clearRect(0, 0, canvas.width, canvas.height);
  cx.lineWidth = SW;
  cx.beginPath();
  cx.moveTo(100, 0+.5*SW);
  cx.lineTo(100, 300-.5*SW);
  cx.stroke();

  let num = document.getElementById('num').value;
  while (num.length < 4) num = '0' + num;  // fills leading zeros to $num

  /***********************\
  |        POINTS:        |
  | ********************* |
  |                       |
  |     a --- b --- c     |
  |     |     |     |     |
  |     d --- e --- f     |
  |     |     |     |     |
  |     g --- h --- i     |
  |     |     |     |     |
  |     j --- k --- l     |
  |                       |
  \***********************/
  let
  a = [0+SW,   0+SW],   b = [100,   0+SW],   c = [200-SW,   0+SW],
  d = [0+SW,    100],   e = [100,    100],   f = [200-SW,    100],
  g = [0+SW,    200],   h = [100,    200],   i = [200-SW,    200],
  j = [0+SW, 300-SW],   k = [100, 300-SW],   l = [200-SW, 300-SW];

  function draw() {
    let x = 1;
    cx.beginPath();
    cx.moveTo(arguments[0][0], arguments[0][1]);
    while (x < arguments.length) {
      cx.lineTo(arguments[x][0], arguments[x][1]);
      x++;
    }
    cx.stroke();
  }

  // 1000s
  switch (num[0]) {
    case '1': draw(j, k);       break;       case '2': draw(g, h);    break;
    case '3': draw(g, k);       break;       case '4': draw(j, h);    break;
    case '5': draw(k, j, h);    break;       case '6': draw(g, j);    break;
    case '7': draw(g, j, k);    break;       case '8': draw(j, g, h); break;
    case '9': draw(h, g, j, k); break;
  }
  // 100s
  switch (num[1]) {
    case '1': draw(k, l);       break;       case '2': draw(h, i);    break;
    case '3': draw(k, i);       break;       case '4': draw(h, l);    break;
    case '5': draw(h, l, k);    break;       case '6': draw(i, l);    break;
    case '7': draw(k, l, i);    break;       case '8': draw(h, i, l); break;
    case '9': draw(h, i, l, k); break;
  }
  // 10s
  switch (num[2]) {
    case '1': draw(a, b);       break;       case '2': draw(d, e);    break;
    case '3': draw(d, b);       break;       case '4': draw(a, e);    break;
    case '5': draw(b, a, e);    break;       case '6': draw(a, d);    break;
    case '7': draw(d, a, b);    break;       case '8': draw(a, d, e); break;
    case '9': draw(b, a, d, e); break;
  }
  // 1s
  switch (num[3]) {
    case '1': draw(b, c);       break;       case '2': draw(e, f);    break;
    case '3': draw(b, f);       break;       case '4': draw(e, c);    break;
    case '5': draw(b, c, e);    break;       case '6': draw(c, f);    break;
    case '7': draw(b, c, f);    break;       case '8': draw(e, f, c); break;
    case '9': draw(b, c, f, e); break;
  }
}


declare
  class Something
     feat
        name %% immutable, public attribute (called a "feature")
     attr
        count %% mutable, private attribute

     %% public method which is used as an initializer
     meth init(N)
        self.name = N
        count := 0
     end

     %% public method
     meth increase
        count := @count + 1
     end
  end
in
  %% create an instance
  Object = {New Something init("object")}

  %% call a method
  {Object increase}


{
     # a class is a package (i.e. a namespace) with methods in it
    package MyClass;

     # a constructor is a function that returns a blessed reference
    sub new {
        my $class = shift;
        bless {variable => 0}, $class;
         # the instance object is a hashref in disguise.
         # (it can be a ref to anything.)
    }

     # an instance method is a function that takes an object as first argument.
     # the -> invocation syntax takes care of that nicely, see Usage paragraph below.
    sub some_method {
        my $self = shift;
        $self->{variable} = 1;
    }
}


with javascript_semantics
function circular(integer p)
    integer len = length(sprintf("%d",p)),
            pow = power(10,len-1),
            p0 = p
    for i=1 to len-1 do
        p = pow*remainder(p,10)+floor(p/10)
        if p<p0 or not is_prime(p) then return false end if
    end for
    return true
end function

sequence c = {}
integer n = 1
while length(c)<19 do
    integer p = get_prime(n)
    if circular(p) then c &= p end if
    n += 1
end while
printf(1,"The first 19 circular primes are:\n%v\n\n",{c})

include mpfr.e
procedure repunit(mpz z, integer n)
    mpz_set_str(z,repeat('1',n))
end procedure

c = {}
n = 7
mpz z = mpz_init()
while length(c)<4 do
    repunit(z,n)
    if mpz_prime(z) then
        c = append(c,sprintf("R(%d)",n))
    end if
    n += 1
end while
printf(1,"The next 4 circular primes, in repunit format, are:\n%s\n\n",{join(c)})


using Gtk, Cairo

const can = GtkCanvas(800, 100)
const win = GtkWindow(can, "Canvas")
const numbers = [0, 1, 20, 300, 4000, 5555, 6789, 8123]

function drawcnum(ctx, xypairs)
    move_to(ctx, xypairs[1][1], xypairs[1][2])
    for p in xypairs[2:end]
        line_to(ctx, p[1], p[2])
    end
    stroke(ctx)
end

@guarded draw(can) do widget
    ctx = getgc(can)
    hlen, wlen, len = height(can), width(can), length(numbers)
    halfwspan, thirdcolspan, voffset = wlen ÷ (len * 2), wlen ÷ (len * 3), hlen ÷ 8
    set_source_rgb(ctx, 0, 0, 2550)
    for (i, n) in enumerate(numbers)
        # paint vertical as width 2 rectangle
        x = halfwspan * (2 * i - 1)
        rectangle(ctx, x, voffset, 2, hlen - 2 * voffset)
        stroke(ctx)
        # determine quadrant and draw numeral lines there
        dig = [(10^(i - 1), m) for (i, m) in enumerate(digits(n))]
        for (d, m) in dig
            y, dx, dy = (d == 1) ? (voffset, thirdcolspan, thirdcolspan) :
                (d == 10) ? (voffset, -thirdcolspan, thirdcolspan) :
                (d == 100) ? (hlen - voffset, thirdcolspan, -thirdcolspan) :
                (hlen - voffset, -thirdcolspan, -thirdcolspan)
            m == 1 && drawcnum(ctx, [[x, y], [x + dx, y]])
            m == 2 && drawcnum(ctx, [[x, y + dy], [x + dx, y + dy]])
            m == 3 && drawcnum(ctx, [[x, y], [x + dx, y + dy]])
            m == 4 && drawcnum(ctx, [[x, y + dy], [x + dx, y]])
            m == 5 && drawcnum(ctx, [[x, y + dy], [x + dx, y], [x, y]])
            m == 6 && drawcnum(ctx, [[x + dx, y], [x + dx, y + dy]])
            m == 7 && drawcnum(ctx, [[x, y], [x + dx, y], [x + dx, y + dy]])
            m == 8 && drawcnum(ctx, [[x, y + dy], [x + dx, y + dy], [x + dx, y]])
            m == 9 && drawcnum(ctx, [[x, y], [x + dx, y], [x + dx, y + dy], [x, y + dy]])
        end
        move_to(ctx, x - halfwspan ÷ 6, hlen - 4)
        Cairo.show_text(ctx, string(n))
        stroke(ctx)
    end
end

function mooncipher()
    draw(can)
    cond = Condition()
    endit(w) = notify(cond)
    signal_connect(endit, win, :destroy)
    show(can)
    wait(cond)
end

mooncipher()


import java.io.StringWriter

class Cistercian() {
    constructor(number: Int) : this() {
        draw(number)
    }

    private val size = 15
    private var canvas = Array(size) { Array(size) { ' ' } }

    init {
        initN()
    }

    private fun initN() {
        for (row in canvas) {
            row.fill(' ')
            row[5] = 'x'
        }
    }

    private fun horizontal(c1: Int, c2: Int, r: Int) {
        for (c in c1..c2) {
            canvas[r][c] = 'x'
        }
    }

    private fun vertical(r1: Int, r2: Int, c: Int) {
        for (r in r1..r2) {
            canvas[r][c] = 'x'
        }
    }

    private fun diagd(c1: Int, c2: Int, r: Int) {
        for (c in c1..c2) {
            canvas[r + c - c1][c] = 'x'
        }
    }

    private fun diagu(c1: Int, c2: Int, r: Int) {
        for (c in c1..c2) {
            canvas[r - c + c1][c] = 'x'
        }
    }

    private fun drawPart(v: Int) {
        when (v) {
            1 -> {
                horizontal(6, 10, 0)
            }
            2 -> {
                horizontal(6, 10, 4)
            }
            3 -> {
                diagd(6, 10, 0)
            }
            4 -> {
                diagu(6, 10, 4)
            }
            5 -> {
                drawPart(1)
                drawPart(4)
            }
            6 -> {
                vertical(0, 4, 10)
            }
            7 -> {
                drawPart(1)
                drawPart(6)
            }
            8 -> {
                drawPart(2)
                drawPart(6)
            }
            9 -> {
                drawPart(1)
                drawPart(8)
            }

            10 -> {
                horizontal(0, 4, 0)
            }
            20 -> {
                horizontal(0, 4, 4)
            }
            30 -> {
                diagu(0, 4, 4)
            }
            40 -> {
                diagd(0, 4, 0)
            }
            50 -> {
                drawPart(10)
                drawPart(40)
            }
            60 -> {
                vertical(0, 4, 0)
            }
            70 -> {
                drawPart(10)
                drawPart(60)
            }
            80 -> {
                drawPart(20)
                drawPart(60)
            }
            90 -> {
                drawPart(10)
                drawPart(80)
            }

            100 -> {
                horizontal(6, 10, 14)
            }
            200 -> {
                horizontal(6, 10, 10)
            }
            300 -> {
                diagu(6, 10, 14)
            }
            400 -> {
                diagd(6, 10, 10)
            }
            500 -> {
                drawPart(100)
                drawPart(400)
            }
            600 -> {
                vertical(10, 14, 10)
            }
            700 -> {
                drawPart(100)
                drawPart(600)
            }
            800 -> {
                drawPart(200)
                drawPart(600)
            }
            900 -> {
                drawPart(100)
                drawPart(800)
            }

            1000 -> {
                horizontal(0, 4, 14)
            }
            2000 -> {
                horizontal(0, 4, 10)
            }
            3000 -> {
                diagd(0, 4, 10)
            }
            4000 -> {
                diagu(0, 4, 14)
            }
            5000 -> {
                drawPart(1000)
                drawPart(4000)
            }
            6000 -> {
                vertical(10, 14, 0)
            }
            7000 -> {
                drawPart(1000)
                drawPart(6000)
            }
            8000 -> {
                drawPart(2000)
                drawPart(6000)
            }
            9000 -> {
                drawPart(1000)
                drawPart(8000)
            }
        }
    }

    private fun draw(v: Int) {
        var v2 = v

        val thousands = v2 / 1000
        v2 %= 1000

        val hundreds = v2 / 100
        v2 %= 100

        val tens = v2 / 10
        val ones = v % 10

        if (thousands > 0) {
            drawPart(1000 * thousands)
        }
        if (hundreds > 0) {
            drawPart(100 * hundreds)
        }
        if (tens > 0) {
            drawPart(10 * tens)
        }
        if (ones > 0) {
            drawPart(ones)
        }
    }

    override fun toString(): String {
        val sw = StringWriter()
        for (row in canvas) {
            for (cell in row) {
                sw.append(cell)
            }
            sw.appendLine()
        }
        return sw.toString()
    }
}

fun main() {
    for (number in arrayOf(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {
        println("$number:")

        val c = Cistercian(number)
        println(c)
    }

}


without js -- (else cffi namespaces error, classes not supported by pwa/p2js anyway)
requires ("1.0.2") -- (free up the temp used in the v.show() call)

class five nullable
    private integer n = 3
    function get_n()
        return n
    end function
    procedure set_n(integer n)
        this.n = n
    end procedure
    procedure show()
        printf(1,"show: n is %d\n",{n})
    end procedure
    function five(integer n = 4)
        printf(1,"constructor five(%d) called\n",n)
        this.n = n
        return this
    end function
    procedure ~five()
        printf(1,"destructor ~five(%d) called\n",n)
    end procedure
end class
five v = new({5})
assert(v.n=5)
v.n = 6
v.show()
v=NULL


?- use_module(library(primality)).

circular(N) :- member(N, [2, 3, 5, 7]).
circular(N) :-
    limit(15, (
        candidate(N),
        N > 9,
        circular_prime(N))).
circular(r(K)) :-
    between(6, inf, K),
    N is (10**K - 1) div 9,
    prime(N).

candidate(0).
candidate(N) :-
    candidate(M),
    member(D, [1, 3, 7, 9]),
    N is 10*M + D.

circular_prime(N) :-
    K is floor(log10(N)) + 1,
    circular_prime(N, N, K).
circular_prime(_, _, 0) :- !.
circular_prime(P0, P, K) :-
   P >= P0,
   prime(P),
   rotate(P, Q), succ(DecK, K),
   circular_prime(P0, Q, DecK).

rotate(N, M) :-
    D is floor(log10(N)),
    divmod(N, 10, Q, R),
    M is R*10**D + Q.

main :-
    findall(P, limit(23, circular(P)), S),
    format("The first 23 circular primes:~n~w~n", [S]),
    halt.

?- main.


function initN()
    local n = {}
    for i=1,15 do
        n[i] = {}
        for j=1,11 do
            n[i][j] = " "
        end
        n[i][6] = "x"
    end
    return n
end

function horiz(n, c1, c2, r)
    for c=c1,c2 do
        n[r+1][c+1] = "x"
    end
end

function verti(n, r1, r2, c)
    for r=r1,r2 do
        n[r+1][c+1] = "x"
    end
end

function diagd(n, c1, c2, r)
    for c=c1,c2 do
        n[r+c-c1+1][c+1] = "x"
    end
end

function diagu(n, c1, c2, r)
    for c=c1,c2 do
        n[r-c+c1+1][c+1] = "x"
    end
end

function initDraw()
    local draw = {}

    draw[1] = function(n) horiz(n, 6, 10, 0) end
    draw[2] = function(n) horiz(n, 6, 10, 4) end
    draw[3] = function(n) diagd(n, 6, 10, 0) end
    draw[4] = function(n) diagu(n, 6, 10, 4) end
    draw[5] = function(n) draw[1](n) draw[4](n) end
    draw[6] = function(n) verti(n, 0, 4, 10) end
    draw[7] = function(n) draw[1](n) draw[6](n) end
    draw[8] = function(n) draw[2](n) draw[6](n) end
    draw[9] = function(n) draw[1](n) draw[8](n) end

    draw[10] = function(n) horiz(n, 0, 4, 0) end
    draw[20] = function(n) horiz(n, 0, 4, 4) end
    draw[30] = function(n) diagu(n, 0, 4, 4) end
    draw[40] = function(n) diagd(n, 0, 4, 0) end
    draw[50] = function(n) draw[10](n) draw[40](n) end
    draw[60] = function(n) verti(n, 0, 4, 0) end
    draw[70] = function(n) draw[10](n) draw[60](n) end
    draw[80] = function(n) draw[20](n) draw[60](n) end
    draw[90] = function(n) draw[10](n) draw[80](n) end

    draw[100] = function(n) horiz(n, 6, 10, 14) end
    draw[200] = function(n) horiz(n, 6, 10, 10) end
    draw[300] = function(n) diagu(n, 6, 10, 14) end
    draw[400] = function(n) diagd(n, 6, 10, 10) end
    draw[500] = function(n) draw[100](n) draw[400](n) end
    draw[600] = function(n) verti(n, 10, 14, 10) end
    draw[700] = function(n) draw[100](n) draw[600](n) end
    draw[800] = function(n) draw[200](n) draw[600](n) end
    draw[900] = function(n) draw[100](n) draw[800](n) end

    draw[1000] = function(n) horiz(n, 0, 4, 14) end
    draw[2000] = function(n) horiz(n, 0, 4, 10) end
    draw[3000] = function(n) diagd(n, 0, 4, 10) end
    draw[4000] = function(n) diagu(n, 0, 4, 14) end
    draw[5000] = function(n) draw[1000](n) draw[4000](n) end
    draw[6000] = function(n) verti(n, 10, 14, 0) end
    draw[7000] = function(n) draw[1000](n) draw[6000](n) end
    draw[8000] = function(n) draw[2000](n) draw[6000](n) end
    draw[9000] = function(n) draw[1000](n) draw[8000](n) end

    return draw
end

function printNumeral(n)
    for i,v in pairs(n) do
        for j,w in pairs(v) do
            io.write(w .. " ")
        end
        print()
    end
    print()
end

function main()
    local draw = initDraw()
    for i,number in pairs({0, 1, 20, 300, 4000, 5555, 6789, 9999}) do
        local n = initN()
        print(number..":")
        local thousands = math.floor(number / 1000)
        number = number % 1000
        local hundreds = math.floor(number / 100)
        number = number % 100
        local tens = math.floor(number / 10)
        local ones = number % 10
        if thousands > 0 then
            draw[thousands * 1000](n)
        end
        if hundreds > 0 then
            draw[hundreds * 100](n)
        end
        if tens > 0 then
            draw[tens * 10](n)
        end
        if ones > 0 then
            draw[ones](n)
        end
        printNumeral(n)
    end
end

main()


module classes;

extern printf;

class @MyClass {
	field @Integer myField { get:get_myField, set:set_myField };

	new [
		this.set_myField(2);
	]

	@Void method [
		this.set_myField(this::get_myField + 1);
	]
};

@Integer main [
	var obj = new @MyClass;
	printf("obj.myField: %i\n", obj::get_myField);
	obj::method;
	printf("obj.myField: %i\n", obj::get_myField);
	return 0;
]


class MyClass {
    public static $classVar;
    public $instanceVar; // can also initialize it here
    function __construct() {
        $this->instanceVar = 0;
    }
    function someMethod() {
        $this->instanceVar = 1;
        self::$classVar = 3;
    }
}
$myObj = new MyClass();


(class +Rectangle)
# dx dy

(dm area> ()  # Define a a method that calculates the rectangle's area
   (* (: dx) (: dy)) )

(println  # Create a rectangle, and print its area
   (area> (new '(+Rectangle) 'dx 3 'dy 4)) )


import random

def is_Prime(n):
    """
    Miller-Rabin primality test.

    A return value of False means n is certainly not prime. A return value of
    True means n is very likely a prime.
    """
    if n!=int(n):
        return False
    n=int(n)
    #Miller-Rabin test for prime
    if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
        return False

    if n==2 or n==3 or n==5 or n==7:
        return True
    s = 0
    d = n-1
    while d%2==0:
        d>>=1
        s+=1
    assert(2**s * d == n-1)

    def trial_composite(a):
        if pow(a, d, n) == 1:
            return False
        for i in range(s):
            if pow(a, 2**i * d, n) == n-1:
                return False
        return True

    for i in range(8):#number of trials
        a = random.randrange(2, n)
        if trial_composite(a):
            return False

    return True

def isPrime(n: int) -> bool:
    '''
        https://www.geeksforgeeks.org/python-program-to-check-whether-a-number-is-prime-or-not/
    '''
    # Corner cases
    if (n <= 1) :
        return False
    if (n <= 3) :
        return True
    # This is checked so that we can skip
    # middle five numbers in below loop
    if (n % 2 == 0 or n % 3 == 0) :
        return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

def rotations(n: int)-> set((int,)):
    '''
        >>> {123, 231, 312} == rotations(123)
        True
    '''
    a = str(n)
    return set(int(a[i:] + a[:i]) for i in range(len(a)))

def isCircular(n: int) -> bool:
    '''
        >>> [isCircular(n) for n in (11, 31, 47,)]
	[True, True, False]
    '''
    return all(isPrime(int(o)) for o in rotations(n))

from itertools import product

def main():
    result = [2, 3, 5, 7]
    first = '137'
    latter = '1379'
    for i in range(1, 6):
        s = set(int(''.join(a)) for a in product(first, *((latter,) * i)))
        while s:
            a = s.pop()
            b = rotations(a)
            if isCircular(a):
                result.append(min(b))
            s -= b
    result.sort()
    return result

assert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main()

repunit = lambda n: int('1' * n)

def repmain(n: int) -> list:
    '''
        returns the first n repunit primes, probably.
    '''
    result = []
    i = 2
    while len(result) < n:
        if is_Prime(repunit(i)):
            result.append(i)
        i += 1
    return result

assert [2, 19, 23, 317, 1031] == repmain(5)

# because this Miller-Rabin test is already on rosettacode there's no good reason to test the longer repunits.


ClearAll[CistercianNumberEncodeHelper, CistercianNumberEncode]
\[Delta] = 0.25;
CistercianNumberEncodeHelper[0] := {}
CistercianNumberEncodeHelper[1] := Line[{{0, 1}, {\[Delta], 1}}]
CistercianNumberEncodeHelper[2] := Line[{{0, 1 - \[Delta]}, {\[Delta], 1 - \[Delta]}}]
CistercianNumberEncodeHelper[3] := Line[{{0, 1}, {\[Delta], 1 - \[Delta]}}]
CistercianNumberEncodeHelper[4] := Line[{{0, 1 - \[Delta]}, {\[Delta], 1}}]
CistercianNumberEncodeHelper[5] := Line[{{0, 1 - \[Delta]}, {\[Delta], 1}, {0, 1}}]
CistercianNumberEncodeHelper[6] := Line[{{\[Delta], 1 - \[Delta]}, {\[Delta], 1}}]
CistercianNumberEncodeHelper[7] := Line[{{\[Delta], 1 - \[Delta]}, {\[Delta], 1}, {0, 1}}]
CistercianNumberEncodeHelper[8] := Line[{{0, 1 - \[Delta]}, {\[Delta], 1 - \[Delta]}, {\[Delta], 1}}]
CistercianNumberEncodeHelper[9] := Line[{{0, 1}, {\[Delta], 1}, {\[Delta], 1 - \[Delta]}, {0, 1 - \[Delta]}}]
CistercianNumberEncode::nnarg = "The argument `1` should be an integer between 0 and 9999 (inclusive).";
CistercianNumberEncode[n_Integer] := Module[{digs},
  If[0 <= n <= 9999,
   digs = IntegerDigits[n, 10, 4];
   Graphics[{Line[{{0, 0}, {0, 1}}],
     CistercianNumberEncodeHelper[digs[[4]]],
     GeometricTransformation[CistercianNumberEncodeHelper[digs[[3]]],
      ReflectionTransform[{1, 0}]],
     GeometricTransformation[CistercianNumberEncodeHelper[digs[[2]]],
      ReflectionTransform[{0, 1}, {0, 1/2}]],
     GeometricTransformation[CistercianNumberEncodeHelper[digs[[1]]],
      RotationTransform[Pi, {0, 1/2}]]
     },
    PlotRange -> {{-1.5 \[Delta], 1.5 \[Delta]}, {0 - 0.5 \[Delta],
       1 + 0.5 \[Delta]}},
    ImageSize -> 50
    ]
   ,
   Message[CistercianNumberEncode::nnarg, n]
   ]
  ]
CistercianNumberEncode[0]
CistercianNumberEncode[1]
CistercianNumberEncode[20]
CistercianNumberEncode[300]
CistercianNumberEncode[4000]
CistercianNumberEncode[5555]
CistercianNumberEncode[6789]
CistercianNumberEncode[1337]


const Size = 15

type Canvas = array[Size, array[Size, char]]

func horizontal(canvas: var Canvas; col1, col2, row: Natural) =
  for col in col1..col2:
    canvas[row][col] = 'x'

func vertical(canvas: var Canvas; row1, row2, col: Natural) =
  for row in row1..row2:
    canvas[row][col] = 'x'

func diagd(canvas: var Canvas; col1, col2, row: Natural) =
  for col in col1..col2:
    canvas[row + col - col1][col] = 'x'

func diagu(canvas: var Canvas; col1, col2, row: Natural) =
  for col in col1..col2:
    canvas[row - col + col1][col] = 'x'

func drawPart(canvas: var Canvas; value: Natural) =

  case value
  of 1:
    canvas.horizontal(6, 10, 0)
  of 2:
    canvas.horizontal(6, 10, 4)
  of 3:
    canvas.diagd(6, 10, 0)
  of 4:
    canvas.diagu(6, 10, 4)
  of 5:
    canvas.drawPart(1)
    canvas.drawPart(4)
  of 6:
    canvas.vertical(0, 4, 10)
  of 7:
    canvas.drawPart(1)
    canvas.drawPart(6)
  of 8:
    canvas.drawPart(2)
    canvas.drawPart(6)
  of 9:
    canvas.drawPart(1)
    canvas.drawPart(8)
  of 10:
    canvas.horizontal(0, 4, 0)
  of 20:
    canvas.horizontal(0, 4, 4)
  of 30:
    canvas.diagu(0, 4, 4)
  of 40:
    canvas.diagd(0, 4, 0)
  of 50:
    canvas.drawPart(10)
    canvas.drawPart(40)
  of 60:
    canvas.vertical(0, 4, 0)
  of 70:
    canvas.drawPart(10)
    canvas.drawPart(60)
  of 80:
    canvas.drawPart(20)
    canvas.drawPart(60)
  of 90:
    canvas.drawPart(10)
    canvas.drawPart(80)
  of 100:
    canvas.horizontal(6, 10, 14)
  of 200:
    canvas.horizontal(6, 10, 10)
  of 300:
    canvas.diagu(6, 10, 14)
  of 400:
    canvas.diagd(6, 10, 10)
  of 500:
    canvas.drawPart(100)
    canvas.drawPart(400)
  of 600:
    canvas.vertical(10, 14, 10)
  of 700:
    canvas.drawPart(100)
    canvas.drawPart(600)
  of 800:
    canvas.drawPart(200)
    canvas.drawPart(600)
  of 900:
    canvas.drawPart(100)
    canvas.drawPart(800)
  of 1000:
    canvas.horizontal(0, 4, 14)
  of 2000:
    canvas.horizontal(0, 4, 10)
  of 3000:
    canvas.diagd(0, 4, 10)
  of 4000:
    canvas.diagu(0, 4, 14)
  of 5000:
    canvas.drawPart(1000)
    canvas.drawPart(4000)
  of 6000:
    canvas.vertical(10, 14, 0)
  of 7000:
    canvas.drawPart(1000)
    canvas.drawPart(6000)
  of 8000:
    canvas.drawPart(2000)
    canvas.drawPart(6000)
  of 9000:
    canvas.drawPart(1000)
    canvas.drawPart(8000)
  else:
    raise newException(ValueError, "wrong value for 'drawPart'")

func draw(canvas: var Canvas; value: Natural) =

  var val = value
  let thousands = val div 1000
  val = val mod 1000
  let hundreds = val div 100
  val = val mod 100
  let tens = val div 10
  let ones = val mod 10

  if thousands != 0:
    canvas.drawPart(1000 * thousands)
  if hundreds != 0:
    canvas.drawPart(100 * hundreds)
  if tens != 0:
    canvas.drawPart(10 * tens)
  if ones != 0:
    canvas.drawPart(ones)

func cistercian(n: Natural): Canvas =
  for row in result.mitems:
    for cell in row.mitems: cell = ' '
    row[5] = 'x'
  result.draw(n)

proc `$`(canvas: Canvas): string =
  for row in canvas:
    for cell in row:
      result.add cell
    result.add '\n'

when isMainModule:

  for number in [0, 1, 20, 300, 4000, 5555, 6789, 9999]:
    echo number, ':'
    echo cistercian(number)


#!/usr/bin/perl

use strict; # https://rosettacode.org/wiki/Cistercian_numerals
use warnings;

my @pts = ('', qw( 01 23 03 12 012 13 013 132 0132) );
my @dots = qw( 4-0 8-0 4-4 8-4 );

my @images = map { sprintf("%-9s\n", "$_:") . draw($_) }
  0, 1, 20, 300, 4000, 5555, 6789, 1133;
for ( 1 .. 13 )
  {
  s/(.+)\n/ print " $1"; '' /e for @images;
  print "\n";
  }

sub draw
  {
  my $n = shift;
  local $_ = "    #    \n" x 12;
  my $quadrant = 0;
  for my $digit ( reverse split //, sprintf "%04d", $n )
    {
    my ($oldx, $oldy);
    for my $cell ( split //, $pts[$digit] )
      {
      my ($x, $y) = split /-/, $dots[$cell];
      if( defined $oldx )
        {
        my $dirx = $x <=> $oldx;
        my $diry = $y <=> $oldy;
        for my $place ( 0 .. 3 )
          {
          substr $_, $oldx + $oldy * 10, 1, '#';
          $oldx += $dirx;
          $oldy += $diry;
          }
        }
      ($oldx, $oldy) = ($x, $y);
      }
    s/.+/ reverse $& /ge;
    ++$quadrant & 1 or $_ = join '', reverse /.+\n/g;
    }
  return $_;
  }


uses objectclass;
define :class MyClass;
    slot value = 1;
enddefine;


programa {
    inclua biblioteca Objetos --> obj

    // "constructor" returns address of object
    funcao inteiro my_class_new(inteiro value) {
        inteiro this = obj.criar_objeto()
        obj.atribuir_propriedade(this, "variable", value) // add property to object
        retorne this
    }

    // "method" takes the address returned by criar_objeto
    funcao my_class_some_method(inteiro this) {
        my_class_set_variable(this, 1)
    }

    // "setter"
    funcao my_class_set_variable(inteiro this, inteiro value) {
        obj.atribuir_propriedade(this, "variable", value)
    }

    // "getter"
    funcao inteiro my_class_get_variable(inteiro this) {
        retorne obj.obter_propriedade_tipo_inteiro(this, "variable")
    }

    funcao inicio() {
        inteiro this = my_class_new(0)

        escreva("variable = ", my_class_get_variable(this), "\n")

        my_class_some_method(this)

        escreva("variable = ", my_class_get_variable(this), "\n")

        my_class_set_variable(this, 99)

        escreva("variable = ", my_class_get_variable(this), "\n")

        obj.liberar_objeto(this)
    }
}


Add-Type -Language CSharp -TypeDefinition @'
public class MyClass
{
    public MyClass()
    {
    }
    public void SomeMethod()
    {
    }
    private int _variable;
    public int Variable
    {
        get { return _variable; }
        set { _variable = value; }
    }
    public static void Main()
    {
        // instantiate it
        MyClass instance = new MyClass();
        // invoke the method
        instance.SomeMethod();
        // set the variable
        instance.Variable = 99;
        // get the variable
        System.Console.WriteLine( "Variable=" + instance.Variable.ToString() );
    }
}
'@


sub isCircular(\n) {
   return False unless n.is-prime;
   my @circular = n.comb;
   return False if @circular.min < @circular[0];
   for 1 ..^ @circular -> $i {
      return False unless .is-prime and $_ >= n given @circular.rotate($i).join;
   }
   True
}

say "The first 19 circular primes are:";
say ((2..*).hyper.grep: { isCircular $_ })[^19];

say "\nThe next 4 circular primes, in repunit format, are:";
loop ( my $i = 7, my $count = 0; $count < 4; $i++ ) {
   ++$count, say "R($i)" if (1 x $i).is-prime
}

use ntheory:from<Perl5> qw[is_prime];

say "\nRepunit testing:";

(5003, 9887, 15073, 25031, 35317, 49081).map: {
    my $now = now;
    say "R($_): Prime? ", ?is_prime("{1 x $_}"), "  {(now - $now).fmt: '%.2f'}"
}


/*REXX program finds & displays circular primes (with a title & in a horizontal format).*/
parse arg N hp .                                 /*obtain optional arguments from the CL*/
if  N=='' |  N==","  then N=        19           /* "      "         "   "   "     "    */
if hp=='' | hp==","  then hip= 1000000           /* "      "         "   "   "     "    */
call genP                                        /*gen primes up to  hp      (200,000). */
q= 024568                                        /*digs that most circular P can't have.*/
found= 0;                           $=           /*found:  circular P count; $:  a list.*/
      do j=1  until found==N;       p= @.j       /* [↓]  traipse through all the primes.*/
      if p>9 & verify(p, q, 'M')>0  then iterate /*Does J contain forbidden digs?  Skip.*/
      if \circP(p)                  then iterate /*Not circular?  Then skip this number.*/
      found= found + 1                           /*bump the  count  of circular primes. */
      $= $  p                                    /*add this prime number  ──►  $  list. */
      end   /*j*/                                /*at this point, $ has a leading blank.*/

say center(' first '       found        " circular primes ",  79, '─')
say strip($)
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
circP: procedure expose @. !.;  parse arg x 1 ox /*obtain a prime number to be examined.*/
               do length(x)-1; parse var x f 2 y /*parse  X  number, rotating the digits*/
               x= y || f                         /*construct a new possible circular P. */
               if x<ox  then return 0            /*is number < the original?  ¬ circular*/
               if \!.x  then return 0            /* "    "   not prime?       ¬ circular*/
               end   /*length(x)···*/
       return 1                                  /*passed all tests,  X is a circular P.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19        /*assign Ps; #Ps*/
      !.= 0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1 /*   " primality*/
                           #= 8;  sq.#= @.# **2  /*number of primes so far; prime square*/
       do [email protected].#+4  by 2  to hip;  parse var j  ''  -1  _ /*get last decimal digit of J. */
       if     _==5  then iterate;   if j// 3==0  then iterate;   if j// 7==0  then iterate
       if j//11==0  then iterate;   if j//13==0  then iterate;   if j//17==0  then iterate
           do k=8  while sq.k<=j                 /*divide by some generated odd primes. */
           if j // @.k==0  then iterate j        /*Is J divisible by  P?  Then not prime*/
           end   /*k*/                           /* [↓]  a prime  (J)  has been found.  */
       #= #+1;   !.j= 1;   sq.#= j*j;   @.#= j   /*bump P cnt;  assign P to @.  and  !. */
       end       /*j*/;                 return


class ProgrammingLanguage
{
   // instance variable:
   private String name;
   // constructor (let's use it to give the instance variable a value):
   public ProgrammingLanguage(String name)
   {
      this.name = name;
      // note use of "this" to distinguish the instance variable from the argument
   }
   // a method:
   public void sayHello()
   {
      println("Hello from the programming language " + name);
      // the method has no argument or local variable called "name", so we can omit the "this"
   }
}


Interface OO_Interface ; Interface for any value of this type
  Get.i()
  Set(Value.i)
  ToString.s()
  Destroy()
EndInterface

Structure OO_Structure ; The *VTable structure
  Get.i
  Set.i
  ToString.i
  Destroy.i
EndStructure

Structure OO_Var
  *VirtualTable.OO_Structure
  Value.i
EndStructure

Procedure OO_Get(*Self.OO_Var)
  ProcedureReturn *Self\Value
EndProcedure

Procedure OO_Set(*Self.OO_Var, n)
  *Self\Value = n
EndProcedure

Procedure.s OO_ToString(*Self.OO_Var)
  ProcedureReturn Str(*Self\Value)
EndProcedure

Procedure Create_OO()
  *p.OO_Var=AllocateMemory(SizeOf(OO_Var))
  If *p
    *p\VirtualTable=?VTable
  EndIf
  ProcedureReturn *p
EndProcedure

Procedure OO_Destroy(*Self.OO_Var)
  FreeMemory(*Self)
EndProcedure

DataSection
  VTable:
  Data.i @OO_Get()
  Data.i @OO_Set()
  Data.i @OO_ToString()
  Data.i @OO_Destroy()
EndDataSection

;- Test the code
*Foo.OO_Interface = Create_OO()
*Foo\Set(341)
MessageRequester("Info", "Foo = " + *Foo\ToString() )
*Foo\Destroy()


see "working..." + nl
see "First 19 circular numbers are:" + nl
n = 0
row = 0
Primes = []

while row < 19
      n++
      flag = 1
      nStr = string(n)
      lenStr = len(nStr)
      for m = 1 to lenStr
          leftStr = left(nStr,m)
          rightStr = right(nStr,lenStr-m)
          strOk = rightStr + leftStr
          nOk = number(strOk)
          ind = find(Primes,nOk)
          if ind < 1 and strOk != nStr
             add(Primes,nOk)
          ok
          if not isprimeNumber(nOk) or ind > 0
             flag = 0
             exit
          ok
       next
       if flag = 1
          row++
          see "" + n + " "
          if row%5 = 0
             see nl
          ok
       ok
end

see nl + "done..." + nl

func isPrimeNumber(num)
     if (num <= 1) return 0 ok
     if (num % 2 = 0) and (num != 2) return 0 ok
     for i = 2 to sqrt(num)
	 if (num % i = 0) return 0 ok
     next
     return 1


require 'gmp'
require 'prime'
candidate_primes = Enumerator.new do |y|
  DIGS = [1,3,7,9]
  [2,3,5,7].each{|n| y << n.to_s}
  (2..).each do |size|
    DIGS.repeated_permutation(size) do |perm|
      y << perm.join if (perm == min_rotation(perm)) && GMP::Z(perm.join).probab_prime? > 0
    end
  end
end

def min_rotation(ar) = Array.new(ar.size){|n| ar.rotate(n)}.min

def circular?(num_str)
  chars = num_str.chars
  return GMP::Z(num_str).probab_prime? > 0 if chars.all?("1")
  chars.size.times.all? do
   GMP::Z(chars.rotate!.join).probab_prime? > 0
   # chars.rotate!.join.to_i.prime?
  end
end

puts "First 19 circular primes:"
puts candidate_primes.lazy.select{|cand| circular?(cand)}.take(19).to_a.join(", "),""
puts "First 5 prime repunits:"
reps = Prime.each.lazy.select{|pr| circular?("1"*pr)}.take(5).to_a
puts  reps.map{|r| "R" + r.to_s}.join(", "), ""
[5003, 9887, 15073, 25031].each {|rep| puts "R#{rep} circular_prime ? #{circular?("1"*rep)}" }


To run:
Start up.
Show some example Cistercian numbers.
Wait for the escape key.
Shut down.

To show some example Cistercian numbers:
Put the screen's left plus 1 inch into the context's spot's x.
Clear the screen to the lightest gray color.
Use the black color.
Use the fat pen.
Draw 0.
Draw 1.
Draw 20.
Draw 300.
Draw 4000.
Draw 5555.
Draw 6789.
Draw 9394.
Refresh the screen.

The mirror flag is a flag.

To draw a Cistercian number:
Split the Cistercian number into some thousands and some hundreds and some tens and some ones.
Stroke zero.
Set the mirror flag.
Stroke the ones.
Clear the mirror flag.
Stroke the tens.
Turn around.
Stroke the hundreds.
Set the mirror flag.
Stroke the thousands.
Turn around.
Label the Cistercian number.
Move the context's spot right 1 inch.

To label a Cistercian number:
Save the context.
Move down the half stem plus the small stem.
Imagine a box with the context's spot and the context's spot.
Draw "" then the Cistercian number in the center of the box with the dark gray color.
Restore the context.

Some tens are a number.

Some ones are a number.

To split a number into some thousands and some hundreds and some tens and some ones:
Divide the number by 10 giving a quotient and a remainder.
Put the remainder into the ones.
Divide the quotient by 10 giving another quotient and another remainder.
Put the other remainder into the tens.
Divide the other quotient by 10 giving a third quotient and a third remainder.
Put the third remainder into the hundreds.
Divide the third quotient by 10 giving a fourth quotient and a fourth remainder.
Put the fourth remainder into the thousands.

The small stem is a length equal to 1/6 inch.

The half stem is a length equal to 1/2 inch.

The tail is a length equal to 1/3 inch.

The slanted tail is a length equal to 6/13 inch.

To stroke a number:
Save the context.
If the number is 1, stroke one.
If the number is 2, stroke two.
If the number is 3, stroke three.
If the number is 4, stroke four.
If the number is 5, stroke five.
If the number is 6, stroke six.
If the number is 7, stroke seven.
If the number is 8, stroke eight.
If the number is 9, stroke nine.
Restore the context.

To turn home:
If the mirror flag is set, turn right; exit.
Turn left.

To turn home some fraction of the way:
If the mirror flag is set, turn right the fraction; exit.
Turn left the fraction.

To stroke zero:
Save the context.
Stroke the half stem.
Turn around.
Move the half stem.
Stroke the half stem.
Restore the context.

To stroke one:
Move the half stem.
Turn home.
Stroke the tail.

To stroke two:
Move the small stem.
Turn home.
Stroke the tail.

To stroke three:
Move the half stem.
Turn home 3/8 of the way.
Stroke the slanted tail.

To stroke four:
Move the small stem.
Turn home 1/8 of the way.
Stroke the slanted tail.

To stroke five:
Stroke 1.
Stroke 4.

To stroke six:
Move the half stem.
Turn home.
Move the tail.
Turn home.
Stroke the tail.

To stroke seven:
Stroke 1.
Stroke 6.

To stroke eight:
Stroke 2.
Stroke 6.

To stroke nine:
Stroke 1.
Stroke 8.


# -*- coding: utf-8 -*-
"""
Some UTF-8 chars used:

‾	8254	203E	‾	OVERLINE
┃	9475	2503	 	BOX DRAWINGS HEAVY VERTICAL
╱	9585	2571	 	BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT
╲	9586	2572	 	BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT
◸	9720	25F8	 	UPPER LEFT TRIANGLE
◹	9721	25F9	 	UPPER RIGHT TRIANGLE
◺	9722	25FA	 	LOWER LEFT TRIANGLE
◻	9723	25FB	 	WHITE MEDIUM SQUARE
◿	9727	25FF	 	LOWER RIGHT TRIANGLE

"""

#%% digit sections

def _init():
    "digit sections for forming numbers"
    digi_bits = """
#0  1   2  3  4  5  6   7   8   9
#
 .  ‾   _  ╲  ╱  ◸  .|  ‾|  _|  ◻
#
 .  ‾   _  ╱  ╲  ◹  |.  |‾  |_  ◻
#
 .  _  ‾   ╱  ╲  ◺  .|  _|  ‾|  ◻
#
 .  _  ‾   ╲  ╱  ◿  |.  |_  |‾  ◻

""".strip()

    lines = [[d.replace('.', ' ') for d in ln.strip().split()]
             for ln in digi_bits.strip().split('\n')
             if '#' not in ln]
    formats = '<2 >2 <2 >2'.split()
    digits = [[f"{dig:{f}}" for dig in line]
              for f, line in zip(formats, lines)]

    return digits

_digits = _init()

#%% int to 3-line strings
def _to_digits(n):
    assert 0 <= n < 10_000 and int(n) == n

    return [int(digit) for digit in f"{int(n):04}"][::-1]

def num_to_lines(n):
    global _digits
    d = _to_digits(n)
    lines = [
        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),
        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),
        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),
        ]

    return lines

def cjoin(c1, c2, spaces='   '):
    return [spaces.join(by_row) for by_row in zip(c1, c2)]

#%% main
if __name__ == '__main__':
    #n = 6666
    #print(f"Arabic {n} to Cistercian:\n")
    #print('\n'.join(num_to_lines(n)))

    for pow10 in range(4):
        step = 10 ** pow10
        print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n')
        lines = num_to_lines(step)
        for n in range(step*2, step*10, step):
            lines = cjoin(lines, num_to_lines(n))
        print('\n'.join(lines))

    numbers = [0, 5555, 6789, 6666]
    print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n')
    lines = num_to_lines(numbers[0])
    for n in numbers[1:]:
        lines = cjoin(lines, num_to_lines(n))
    print('\n'.join(lines))


class MyClass:
    name2 = 2 # Class attribute

    def __init__(self):
        """
        Constructor  (Technically an initializer rather than a true "constructor")
        """
        self.name1 = 0 # Instance attribute

    def someMethod(self):
        """
        Method
        """
        self.name1 = 1
        MyClass.name2 = 3

myclass = MyClass() # class name, invoked as a function is the constructor syntax.

class MyOtherClass:
    count = 0  # Population of "MyOtherClass" objects
    def __init__(self, name, gender="Male", age=None):
        """
        One initializer required, others are optional (with different defaults)
        """
        MyOtherClass.count += 1
        self.name = name
        self.gender = gender
        if age is not None:
            self.age = age
    def __del__(self):
        MyOtherClass.count -= 1

person1 = MyOtherClass("John")
print person1.name, person1.gender  # "John Male"
print person1.age                   # Raises AttributeError exception!
person2 = MyOtherClass("Jane", "Female", 23)
print person2.name, person2.gender, person2.age  # "Jane Female 23"


#You define a class simply by setting the class attribute of an object
circS3 <- list(radius=5.5, centre=c(3, 4.2))
class(circS3) <- "circle"

#plot is a generic function, so we can define a class specific method by naming it plot.classname
plot.circle <- function(x, ...)
{
   t <- seq(0, 2*pi, length.out=200)
   plot(x$centre[1] + x$radius*cos(t),
      x$centre[2] + x$radius*sin(t),
      type="l", ...)
}
plot(circS3)


// [dependencies]
// rug = "1.8"

fn is_prime(n: u32) -> bool {
    if n < 2 {
        return false;
    }
    if n % 2 == 0 {
        return n == 2;
    }
    if n % 3 == 0 {
        return n == 3;
    }
    let mut p = 5;
    while p * p <= n {
        if n % p == 0 {
            return false;
        }
        p += 2;
        if n % p == 0 {
            return false;
        }
        p += 4;
    }
    true
}

fn cycle(n: u32) -> u32 {
    let mut m: u32 = n;
    let mut p: u32 = 1;
    while m >= 10 {
        p *= 10;
        m /= 10;
    }
    m + 10 * (n % p)
}

fn is_circular_prime(p: u32) -> bool {
    if !is_prime(p) {
        return false;
    }
    let mut p2: u32 = cycle(p);
    while p2 != p {
        if p2 < p || !is_prime(p2) {
            return false;
        }
        p2 = cycle(p2);
    }
    true
}

fn test_repunit(digits: usize) {
    use rug::{integer::IsPrime, Integer};
    let repunit = "1".repeat(digits);
    let bignum = Integer::from_str_radix(&repunit, 10).unwrap();
    if bignum.is_probably_prime(10) != IsPrime::No {
        println!("R({}) is probably prime.", digits);
    } else {
        println!("R({}) is not prime.", digits);
    }
}

fn main() {
    use rug::{integer::IsPrime, Integer};
    println!("First 19 circular primes:");
    let mut count = 0;
    let mut p: u32 = 2;
    while count < 19 {
        if is_circular_prime(p) {
            if count > 0 {
                print!(", ");
            }
            print!("{}", p);
            count += 1;
        }
        p += 1;
    }
    println!();
    println!("Next 4 circular primes:");
    let mut repunit: u32 = 1;
    let mut digits: usize = 1;
    while repunit < p {
        repunit = 10 * repunit + 1;
        digits += 1;
    }
    let mut bignum = Integer::from(repunit);
    count = 0;
    while count < 4 {
        if bignum.is_probably_prime(15) != IsPrime::No {
            if count > 0 {
                print!(", ");
            }
            print!("R({})", digits);
            count += 1;
        }
        digits += 1;
        bignum = bignum * 10 + 1;
    }
    println!();
    test_repunit(5003);
    test_repunit(9887);
    test_repunit(15073);
    test_repunit(25031);
    test_repunit(35317);
    test_repunit(49081);
}


object CircularPrimes {
  def main(args: Array[String]): Unit = {
    println("First 19 circular primes:")
    var p = 2
    var count = 0
    while (count < 19) {
      if (isCircularPrime(p)) {
        if (count > 0) {
          print(", ")
        }
        print(p)
        count += 1
      }
      p += 1
    }
    println()

    println("Next 4 circular primes:")
    var repunit = 1
    var digits = 1
    while (repunit < p) {
      repunit = 10 * repunit + 1
      digits += 1
    }
    var bignum = BigInt.apply(repunit)
    count = 0
    while (count < 4) {
      if (bignum.isProbablePrime(15)) {
        if (count > 0) {
          print(", ")
        }
        print(s"R($digits)")
        count += 1
      }
      digits += 1
      bignum = bignum * 10
      bignum = bignum + 1
    }
    println()

    testRepunit(5003)
    testRepunit(9887)
    testRepunit(15073)
    testRepunit(25031)
  }

  def isPrime(n: Int): Boolean = {
    if (n < 2) {
      return false
    }
    if (n % 2 == 0) {
      return n == 2
    }
    if (n % 3 == 0) {
      return n == 3
    }
    var p = 5
    while (p * p <= n) {
      if (n % p == 0) {
        return false
      }
      p += 2
      if (n % p == 0) {
        return false
      }
      p += 4
    }
    true
  }

  def cycle(n: Int): Int = {
    var m = n
    var p = 1
    while (m >= 10) {
      p *= 10
      m /= 10
    }
    m + 10 * (n % p)
  }

  def isCircularPrime(p: Int): Boolean = {
    if (!isPrime(p)) {
      return false
    }
    var p2 = cycle(p)
    while (p2 != p) {
      if (p2 < p || !isPrime(p2)) {
        return false
      }
      p2 = cycle(p2)
    }
    true
  }

  def testRepunit(digits: Int): Unit = {
    val ru = repunit(digits)
    if (ru.isProbablePrime(15)) {
      println(s"R($digits) is probably prime.")
    } else {
      println(s"R($digits) is not prime.")
    }
  }

  def repunit(digits: Int): BigInt = {
    val ch = Array.fill(digits)('1')
    BigInt.apply(new String(ch))
  }
}


#lang racket

(define fish%
  (class object%
    (super-new)

    ;; an instance variable & constructor argument
    (init-field size)

    ;; a new method
    (define/public (eat)
      (displayln "gulp!"))))

;; constructing an instance
(new fish% [size 50])


class Camel { has Int $.humps = 1; }

my Camel $a .= new;
say $a.humps;  # Automatically generated accessor method.

my Camel $b .= new: humps => 2;
say $b.humps;


TYPE MyClass EXTENDS QObject
    Variable AS INTEGER

    CONSTRUCTOR
        Variable = 0
    END CONSTRUCTOR

    SUB someMethod
        MyClass.Variable = 1
    END SUB
END TYPE

' create an instance
DIM instance AS MyClass

' invoke the method
instance.someMethod


func is_circular_prime(n) {
    n.is_prime || return false

    var circular = n.digits
    circular.min < circular.tail && return false

    for k in (1 ..^ circular.len) {
        with (circular.rotate(k).digits2num) {|p|
            (p.is_prime && (p >= n)) || return false
        }
    }

    return true
}

say "The first 19 circular primes are:"
say 19.by(is_circular_prime)

say "\nThe next 4 circular primes, in repunit format, are:"
{|n| (10**n - 1)/9 -> is_prob_prime }.first(4, 4..Inf).each {|n|
    say "R(#{n})"
}

say "\nRepunit testing:"
[5003, 9887, 15073, 25031, 35317, 49081].each {|n|
    var now = Time.micro
    say ("R(#{n}) -> ", is_prob_prime((10**n - 1)/9) ? 'probably prime' : 'composite',
        " (took: #{'%.3f' % Time.micro-now} sec)")
}


import "/math" for Int
import "/big" for BigInt
import "/str" for Str

var circs = []

var isCircular = Fn.new { |n|
    var nn = n
    var pow = 1 // will eventually contain 10 ^ d where d is number of digits in n
    while (nn > 0) {
        pow = pow * 10
        nn = (nn/10).floor
    }
    nn = n
    while (true) {
        nn = nn * 10
        var f = (nn/pow).floor // first digit
        nn = nn + f * (1 - pow)
        if (circs.contains(nn)) return false
        if (nn == n) break
        if (!Int.isPrime(nn)) return false
    }
    return true
}

var repunit = Fn.new { |n| BigInt.new(Str.repeat("1", n)) }

System.print("The first 19 circular primes are:")
var digits = [1, 3, 7, 9]
var q = [1, 2, 3, 5, 7, 9]  // queue the numbers to be examined
var fq = [1, 2, 3, 5, 7, 9] // also queue the corresponding first digits
var count = 0
while (true) {
    var f = q[0]   // peek first element
    var fd = fq[0] // peek first digit
    if (Int.isPrime(f) && isCircular.call(f)) {
        circs.add(f)
        count = count + 1
        if (count == 19) break
    }
    q.removeAt(0)  // pop first element
    fq.removeAt(0) // ditto for first digit queue
    if (f != 2 && f != 5) { // if digits > 1 can't contain a 2 or 5
        // add numbers with one more digit to queue
        // only numbers whose last digit >= first digit need be added
        for (d in digits) {
            if (d >= fd) {
                q.add(f*10+d)
                fq.add(fd)
            }
        }
    }
}
System.print(circs)

System.print("\nThe next 4 circular primes, in repunit format, are:")
count = 0
var rus = []
var primes = Int.primeSieve(10000)
for (p in primes[3..-1]) {
     if (repunit.call(p).isProbablePrime(1)) {
        rus.add("R(%(p))")
        count = count + 1
        if (count == 4) break
    }
}
System.print(rus)


/*REXX program displays a (non-negative 4-digit) integer in  Cistercian (monk) numerals.*/
parse arg m                                      /*obtain optional arguments from the CL*/
if m='' | m=","  then m= 0 1 20 300 4000 5555 6789 9393  /*Not specified?  Use defaults.*/
$.=;                     nnn= words(m)
             do j=1  for nnn;   z= word(m, j)            /*process each of the numbers. */
             if \datatype(z, 'W')  then call serr  "number isn't numeric: "           z
             if \datatype(z, 'N')  then call serr  "number isn't an integer: "        z
             z= z / 1                            /*normalize the number:  006  5.0  +4  */
             if z<0                then call serr  "number can't be negative: "       z
             if z>9999             then call serr  "number is too large (>9,999): "   z
             call monk z / 1                     /*create the Cistercian quad numeral.  */
             end   /*j*/
call show                                        /*display   "      "       "     "     */
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@:    parse arg @x,@y;  return @.@x.@y           /*return a value from the point (@x,@y)*/
quad: parse arg #;   if #\==0  then interpret 'call' #;  return       /*build a numeral.*/
serr: say '***error*** '  arg(1);    exit 13                          /*issue error msg.*/
app:   do r= 9 for 10 by -1; do c=-5 for 11; $.r= $.r||@.c.r; end; $.r=$.r b5; end; return
eye:   do a=0  for 10; @.0.a= '│';   end; return /*build an "eye" glyph (vertical axis).*/
p:     do k=1  by 3  until k>arg(); x= arg(k); y= arg(k+1); @.x.y= arg(k+2); end;   return
sect:  do q=1  for 4; call quad s.q; end; return /*build a Cistercian numeral character.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
monk: parse arg n; n= right(n, 4, 0);  @.= ' '   /*zero─fill N;  blank─out numeral grid.*/
      b4= left('', 4);  b5= b4" ";   $.11= $.11  ||  b4  ||  n  ||  b4  ||  b5;   call eye
      parse var n s.4 2 s.3 3 s.2 4 s.1;    call sect;    call nice;    call app;   return
/*──────────────────────────────────────────────────────────────────────────────────────*/
nice: if @(-1, 9)=='─'     then call p 0, 9, "┐";    if @(1,9)=='─'  then call p 0, 9, "┌"
      if @(-1, 9)=='─'  &  @(1,9)=='─'                               then call p 0, 9, "┬"
      if @(-1, 0)=='─'     then call p 0, 0, "┘";    if @(1,0)=='─'  then call p 0, 0, "└"
      if @(-1, 0)=='─'  &  @(1,0)=='─'                               then call p 0, 0, "┴"
         do i=4  to 5
         if @(-1, i)=='─'  then call p 0, i, "┤";    if @(1,i)=='─'  then call p 0, i, "├"
         if @(-1, i)=='─'  &  @(1,i)=="─"                            then call p 0, i, "┼"
         end   /*i*/;                                                               return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show:    do jj= 11  for 10+2  by -1;    say strip($.jj, 'T')  /*display 1 row at a time.*/
         if jj==5  then do 3;           say strip( copies(b5'│'b5 b5, nnn), 'T');     end
         end   /*r*/;                   return
/*──────────────────────────────────────────────────────────────────────────────────────*/
1: ?= '─';  if q==1  then call p  1, 9, ?,  2, 9, ?,  3, 9, ?,  4, 9, ?,  5, 9, ?
            if q==2  then call p -1, 9, ?, -2, 9, ?, -3, 9, ?, -4, 9, ?, -5, 9, ?
            if q==3  then call p  1, 0, ?,  2, 0, ?,  3, 0, ?,  4, 0, ?,  5, 0, ?
            if q==4  then call p -1, 0, ?, -2, 0, ?, -3, 0, ?, -4, 0, ?, -5, 0, ?;  return
/*──────────────────────────────────────────────────────────────────────────────────────*/
2: ?= '─';  if q==1  then call p  1, 5, ?,  2, 5, ?,  3, 5, ?,  4, 5, ?,  5, 5, ?
            if q==2  then call p -1, 5, ?, -2, 5, ?, -3, 5, ?, -4, 5, ?, -5, 5, ?
            if q==3  then call p  1, 4, ?,  2, 4, ?,  3, 4, ?,  4, 4, ?,  5, 4, ?
            if q==4  then call p -1, 4, ?, -2, 4, ?, -3, 4, ?, -4, 4, ?, -5, 4, ?;  return
/*──────────────────────────────────────────────────────────────────────────────────────*/
3: ?= '\';  if q==1  then call p  1, 9, ?,  2, 8, ?,  3, 7, ?,  4, 6, ?,  5, 5, ?
   ?= '/';  if q==2  then call p -1, 9, ?, -2, 8, ?, -3, 7, ?, -4, 6, ?, -5, 5, ?
   ?= '/';  if q==3  then call p  1, 0, ?,  2, 1, ?,  3, 2, ?,  4, 3, ?,  5, 4, ?
   ?= '\';  if q==4  then call p -5, 4, ?, -4, 3, ?, -3, 2, ?, -2, 1, ?, -1, 0, ?;  return
/*──────────────────────────────────────────────────────────────────────────────────────*/
4: ?= '/';  if q==1  then call p  1, 5, ?,  2, 6, ?,  3, 7, ?,  4, 8, ?,  5, 9, ?
   ?= '\';  if q==2  then call p -5, 9, ?, -4, 8, ?, -3, 7, ?, -2, 6, ?, -1, 5, ?
   ?= '\';  if q==3  then call p  1, 4, ?,  2, 3, ?,  3, 2, ?,  4, 1, ?,  5, 0, ?
   ?= '/';  if q==4  then call p -5, 0, ?, -4, 1, ?, -3, 2, ?, -2, 3, ?, -1, 4, ?;  return
/*──────────────────────────────────────────────────────────────────────────────────────*/
5: ?= '/';  if q==1  then call p  1, 5, ?,  2, 6, ?,  3, 7, ?,  4, 8, ?
   ?= '\';  if q==2  then call p -4, 8, ?, -3, 7, ?, -2, 6, ?, -1, 5, ?
   ?= '\';  if q==3  then call p  1, 4, ?,  2, 3, ?,  3, 2, ?,  4, 1, ?
   ?= '/';  if q==4  then call p -4, 1, ?, -3, 2, ?, -2, 3, ?, -1, 4, ?;  call 1;   return
/*──────────────────────────────────────────────────────────────────────────────────────*/
6: ?= '│';  if q==1  then call p  5, 9, ?,  5, 8, ?,  5, 7, ?,  5, 6, ?,  5, 5, ?
            if q==2  then call p -5, 9, ?, -5, 8, ?, -5, 7, ?, -5, 6, ?, -5, 5, ?
            if q==3  then call p  5, 0, ?,  5, 1, ?,  5, 2, ?,  5, 3, ?,  5, 4, ?
            if q==4  then call p -5, 0, ?, -5, 1, ?, -5, 2, ?, -5, 3, ?, -5, 4, ?;  return
/*──────────────────────────────────────────────────────────────────────────────────────*/
7:          call 1;  call 6;         if q==1  then call p  5, 9, '┐'
                                     if q==2  then call p -5, 9, '┌'
                                     if q==3  then call p  5, 0, '┘'
                                     if q==4  then call p -5, 0, '└';               return
/*──────────────────────────────────────────────────────────────────────────────────────*/
8:          call 2;  call 6;         if q==1  then call p  5, 5, '┘'
                                     if q==2  then call p -5, 5, '└'
                                     if q==3  then call p  5, 4, '┐'
                                     if q==4  then call p -5, 4, '┌';               return
/*──────────────────────────────────────────────────────────────────────────────────────*/
9:          call 1; call 2; call 6;  if q==1  then call p  5, 5, '┘',  5, 9, "┐"
                                     if q==2  then call p -5, 5, '└', -5, 9, "┌"
                                     if q==3  then call p  5, 0, '┘',  5, 4, "┐"
                                     if q==4  then call p -5, 0, '└', -5, 4, "┌";   return


class Alpha
    'I am Alpha.' as greeting
    define say_hello
        greeting print

class Beta extend Alpha
    'I am Beta!' as greeting


Class NumberContainer
  Private TheNumber As Integer
  Sub Constructor(InitialNumber As Integer)
    TheNumber = InitialNumber
  End Sub

  Function Number() As Integer
    Return TheNumber
  End Function

  Sub Number(Assigns NewNumber As Integer)
    TheNumber = NewNumber
  End Sub
End Class


rebol [
    Title: "Classes"
    URL: http://rosettacode.org/wiki/Classes
]

; Objects are derived from the base 'object!' type. REBOL uses a
; prototyping object system, so any object can be treated as a class,
; from which to derive others.

cowboy: make object! [
	name: "Tex"  ; Instance variable.
	hi: does [   ; Method.
		print [self/name ": Howdy!"]]
]

; I create two instances of the 'cowboy' class.

tex: make cowboy []
roy: make cowboy [
	name: "Roy"  ; Override 'name' property.
]

print "Say 'hello', boys:"  tex/hi  roy/hi
print ""

; Now I'll subclass 'cowboy'. Subclassing looks a lot like instantiation:

legend: make cowboy [
	deed: "..."
	boast: does [
		print [self/name ": I once" self/deed "!"]]
]

; Instancing the legend:

pecos: make legend [name: "Pecos Bill"  deed: "lassoed a twister"]

print "Howdy, Pecos!"  pecos/hi
print "Tell us about yourself?"  pecos/boast


func IsPrime(N);        \Return 'true' if N > 2 is a prime number
int  N, I;
[if (N&1) = 0 \even number\ then return false;
for I:= 3 to sqrt(N) do
    [if rem(N/I) = 0 then return false;
    I:= I+1;
    ];
return true;
];

func CircPrime(N0);     \Return 'true' if N0 is a circular prime
int  N0, N, Digits, Rotation, I, R;
[N:= N0;
Digits:= 0;             \count number of digits in N
repeat  Digits:= Digits+1;
        N:= N/10;
until   N = 0;
N:= N0;
for Rotation:= 0 to Digits-1 do
    [if not IsPrime(N) then return false;
    N:= N/10;           \rotate least sig digit into high end
    R:= rem(0);
    for I:= 0 to Digits-2 do
        R:= R*10;
    N:= N+R;
    if N0 > N then      \reject N0 if it has a smaller prime rotation
        return false;
    ];
return true;
];

int Counter, N;
[IntOut(0, 2);  ChOut(0, ^ );   \show first circular prime
Counter:= 1;
N:= 3;                          \remaining primes are odd
loop    [if CircPrime(N) then
            [IntOut(0, N);  ChOut(0, ^ );
            Counter:= Counter+1;
            if Counter >= 19 then quit;
            ];
        N:= N+2;
        ];
]


const std = @import("std");
const math = std.math;
const heap = std.heap;
const stdout = std.io.getStdOut().writer();

pub fn main() !void {
    var arena = heap.ArenaAllocator.init(heap.page_allocator);
    defer arena.deinit();

    var candidates = std.PriorityQueue(u32).init(&arena.allocator, u32cmp);
    defer candidates.deinit();

    try stdout.print("The circular primes are:\n", .{});
    try stdout.print("{:10}" ** 4, .{ 2, 3, 5, 7 });

    var c: u32 = 4;
    try candidates.add(0);
    while (true) {
        var n = candidates.remove();
        if (n > 1_000_000)
            break;
        if (n > 10 and circular(n)) {
            try stdout.print("{:10}", .{n});
            c += 1;
            if (c % 10 == 0)
                try stdout.print("\n", .{});
        }
        try candidates.add(10 * n + 1);
        try candidates.add(10 * n + 3);
        try candidates.add(10 * n + 7);
        try candidates.add(10 * n + 9);
    }
    try stdout.print("\n", .{});
}

fn u32cmp(a: u32, b: u32) math.Order {
    return math.order(a, b);
}

fn circular(n0: u32) bool {
    if (!isprime(n0))
        return false
    else {
        var n = n0;
        var d = @floatToInt(u32, @log10(@intToFloat(f32, n)));
        return while (d > 0) : (d -= 1) {
            n = rotate(n);
            if (n < n0 or !isprime(n))
                break false;
        } else true;
    }
}

fn rotate(n: u32) u32 {
    if (n == 0)
        return 0
    else {
        const d = @floatToInt(u32, @log10(@intToFloat(f32, n))); // digit count - 1
        const m = math.pow(u32, 10, d);
        return (n % m) * 10 + n / m;
    }
}

fn isprime(n: u32) bool {
    if (n < 2)
        return false;

    inline for ([3]u3{ 2, 3, 5 }) |p| {
        if (n % p == 0)
            return n == p;
    }

    const wheel235 = [_]u3{
        6, 4, 2, 4, 2, 4, 6, 2,
    };
    var i: u32 = 1;
    var f: u32 = 7;
    return while (f * f <= n) {
        if (n % f == 0)
            break false;
        f += wheel235[i];
        i = (i + 1) & 0x07;
    } else true;
}


def initN
    n = Array.new(15){Array.new(11, ' ')}
    for i in 1..15
        n[i - 1][5] = 'x'
    end
    return n
end

def horiz(n, c1, c2, r)
    for c in c1..c2
        n[r][c] = 'x'
    end
end

def verti(n, r1, r2, c)
    for r in r1..r2
        n[r][c] = 'x'
    end
end

def diagd(n, c1, c2, r)
    for c in c1..c2
        n[r+c-c1][c] = 'x'
    end
end

def diagu(n, c1, c2, r)
    for c in c1..c2
        n[r-c+c1][c] = 'x'
    end
end

def initDraw
    draw = []

    draw[1] = lambda do |n| horiz(n, 6, 10, 0) end
    draw[2] = lambda do |n| horiz(n, 6, 10, 4) end
    draw[3] = lambda do |n| diagd(n, 6, 10, 0) end
    draw[4] = lambda do |n| diagu(n, 6, 10, 4) end
    draw[5] = lambda do |n|
        draw[1].call(n)
        draw[4].call(n)
    end
    draw[6] = lambda do |n| verti(n, 0, 4, 10) end
    draw[7] = lambda do |n|
        draw[1].call(n)
        draw[6].call(n)
    end
    draw[8] = lambda do |n|
        draw[2].call(n)
        draw[6].call(n)
    end
    draw[9] = lambda do |n|
        draw[1].call(n)
        draw[8].call(n)
    end

    draw[10] = lambda do |n| horiz(n, 0, 4, 0) end
    draw[20] = lambda do |n| horiz(n, 0, 4, 4) end
    draw[30] = lambda do |n| diagu(n, 0, 4, 4) end
    draw[40] = lambda do |n| diagd(n, 0, 4, 0) end
    draw[50] = lambda do |n|
        draw[10].call(n)
        draw[40].call(n)
    end
    draw[60] = lambda do |n| verti(n, 0, 4, 0) end
    draw[70] = lambda do |n|
        draw[10].call(n)
        draw[60].call(n)
    end
    draw[80] = lambda do |n|
        draw[20].call(n)
        draw[60].call(n)
    end
    draw[90] = lambda do |n|
        draw[10].call(n)
        draw[80].call(n)
    end

    draw[100] = lambda do |n| horiz(n, 6, 10, 14) end
    draw[200] = lambda do |n| horiz(n, 6, 10, 10) end
    draw[300] = lambda do |n| diagu(n, 6, 10, 14) end
    draw[400] = lambda do |n| diagd(n, 6, 10, 10) end
    draw[500] = lambda do |n|
        draw[100].call(n)
        draw[400].call(n)
    end
    draw[600] = lambda do |n| verti(n, 10, 14, 10) end
    draw[700] = lambda do |n|
        draw[100].call(n)
        draw[600].call(n)
    end
    draw[800] = lambda do |n|
        draw[200].call(n)
        draw[600].call(n)
    end
    draw[900] = lambda do |n|
        draw[100].call(n)
        draw[800].call(n)
    end

    draw[1000] = lambda do |n| horiz(n, 0, 4, 14) end
    draw[2000] = lambda do |n| horiz(n, 0, 4, 10) end
    draw[3000] = lambda do |n| diagd(n, 0, 4, 10) end
    draw[4000] = lambda do |n| diagu(n, 0, 4, 14) end
    draw[5000] = lambda do |n|
        draw[1000].call(n)
        draw[4000].call(n)
    end
    draw[6000] = lambda do |n| verti(n, 10, 14, 0) end
    draw[7000] = lambda do |n|
        draw[1000].call(n)
        draw[6000].call(n)
    end
    draw[8000] = lambda do |n|
        draw[2000].call(n)
        draw[6000].call(n)
    end
    draw[9000] = lambda do |n|
        draw[1000].call(n)
        draw[8000].call(n)
    end

    return draw
end

def printNumeral(n)
    for a in n
        for b in a
            print b
        end
        print "\n"
    end
    print "\n"
end

draw = initDraw()
for number in [0, 1, 20, 300, 4000, 5555, 6789, 9999]
    n = initN()
    print number, ":\n"

    thousands = (number / 1000).floor
    number = number % 1000

    hundreds = (number / 100).floor
    number = number % 100

    tens = (number / 10).floor
    ones = number % 10

    if thousands > 0 then
        draw[thousands * 1000].call(n)
    end
    if hundreds > 0 then
        draw[hundreds * 100].call(n)
    end
    if tens > 0 then
        draw[tens * 10].call(n)
    end
    if ones > 0 then
        draw[ones].call(n)
    end
    printNumeral(n)
end


New point { x=10  y=20  z=30  print() }
Class Point x y z func print see x + nl + y + nl + z + nl


class MyClass

  def initialize
    @instance_var = 0
  end

  def add_1
    @instance_var += 1
  end

end

my_class = MyClass.new #allocates an object and calls it's initialize method, then returns it.


struct MyClass {
    variable: i32, // member variable = instance variable
}

impl MyClass {
    // member function = method, with its implementation
    fn some_method(&mut self) {
        self.variable = 1;
    }

    // constructor, with its implementation
    fn new() -> MyClass {
        // Here could be more code.
        MyClass { variable: 0 }
    }
}

fn main () {
    // Create an instance in the stack.
    let mut instance = MyClass::new();

    // Create an instance in the heap.
    let mut p_instance = Box::new(MyClass::new());

    // Invoke method on both istances,
    instance.some_method();
    p_instance.some_method();

    // Both instances are automatically deleted when their scope ends.
}


import "/fmt" for Fmt

var n

var init = Fn.new {
    n = List.filled(15, null)
    for (i in 0..14) {
        n[i] = List.filled(11, " ")
        n[i][5] = "x"
    }
}

var horiz = Fn.new { |c1, c2, r| (c1..c2).each { |c| n[r][c] = "x" } }
var verti = Fn.new { |r1, r2, c| (r1..r2).each { |r| n[r][c] = "x" } }
var diagd = Fn.new { |c1, c2, r| (c1..c2).each { |c| n[r+c-c1][c] = "x" } }
var diagu = Fn.new { |c1, c2, r| (c1..c2).each { |c| n[r-c+c1][c] = "x" } }

var draw // map contains recursive closures
draw = {
    1: Fn.new { horiz.call(6, 10, 0) },
    2: Fn.new { horiz.call(6, 10, 4) },
    3: Fn.new { diagd.call(6, 10, 0) },
    4: Fn.new { diagu.call(6, 10, 4) },
    5: Fn.new {
           draw[1].call()
           draw[4].call()
       },
    6: Fn.new { verti.call(0, 4, 10) },
    7: Fn.new {
           draw[1].call()
           draw[6].call()
       },
    8: Fn.new {
           draw[2].call()
           draw[6].call()
       },
    9: Fn.new {
           draw[1].call()
           draw[8].call()
       },
    10: Fn.new { horiz.call(0, 4, 0) },
    20: Fn.new { horiz.call(0, 4, 4) },
    30: Fn.new { diagu.call(0, 4, 4) },
    40: Fn.new { diagd.call(0, 4, 0) },
    50: Fn.new {
           draw[10].call()
           draw[40].call()
        },
    60: Fn.new { verti.call(0, 4, 0) },
    70: Fn.new {
           draw[10].call()
           draw[60].call()
        },
    80: Fn.new {
           draw[20].call()
           draw[60].call()
        },
    90: Fn.new {
           draw[10].call()
           draw[80].call()
        },
    100: Fn.new { horiz.call(6, 10, 14) },
    200: Fn.new { horiz.call(6, 10, 10) },
    300: Fn.new { diagu.call(6, 10, 14) },
    400: Fn.new { diagd.call(6, 10, 10) },
    500: Fn.new {
            draw[100].call()
            draw[400].call()
         },
    600: Fn.new { verti.call(10, 14, 10) },
    700: Fn.new {
            draw[100].call()
            draw[600].call()
         },
    800: Fn.new {
            draw[200].call()
            draw[600].call()
         },
    900: Fn.new {
            draw[100].call()
            draw[800].call()
         },
    1000: Fn.new { horiz.call(0, 4, 14) },
    2000: Fn.new { horiz.call(0, 4, 10) },
    3000: Fn.new { diagd.call(0, 4, 10) },
    4000: Fn.new { diagu.call(0, 4, 14) },
    5000: Fn.new {
             draw[1000].call()
             draw[4000].call()
          },
    6000: Fn.new { verti.call(10, 14, 0) },
    7000: Fn.new {
             draw[1000].call()
             draw[6000].call()
          },
    8000: Fn.new {
             draw[2000].call()
             draw[6000].call()
          },
    9000: Fn.new {
             draw[1000].call()
             draw[8000].call()
          }
}

var numbers = [0, 1, 20, 300, 4000, 5555, 6789, 9999]
for (number in numbers) {
    init.call()
    System.print("%(number):")
    var thousands = (number/1000).floor
    number = number % 1000
    var hundreds  = (number/100).floor
    number = number % 100
    var tens = (number/10).floor
    var ones = number % 10
    if (thousands > 0) draw[thousands*1000].call()
    if (hundreds > 0) draw[hundreds*100].call()
    if (tens > 0) draw[tens*10].call()
    if (ones > 0) draw[ones].call()
    Fmt.mprint(n, 1, 0, "")
    System.print()
}


class CLASSTEST is
  readonly attr x:INT; -- give a public getter, not a setter
  private attr y:INT;  -- no getter, no setter
  attr z:INT;          -- getter and setter

  -- constructor
  create(x, y, z:INT):CLASSTEST is
    res :CLASSTEST := new; -- or res ::= new
    res.x := x;
    res.y := y;
    res.z := z;
    return res;
  end;

  -- a getter for the private y summed to s
  getPrivateY(s:INT):INT is
    -- y is not shadowed so we can write y instead of
    -- self.y
    return y + s;
  end;
end;


/** This class implicitly includes a constructor which accepts an Int and
 *  creates "val variable1: Int" with that value.
 */
class MyClass(val myMethod: Int) { // Acts like a getter, getter automatically generated.
  var variable2 = "asdf" // Another instance variable; a public var this time
  def this() = this(0) // An auxilliary constructor that instantiates with a default value
}

object HelloObject {
  val s = "Hello" // Not private, so getter auto-generated
}

/** Demonstrate use of our example class.
 */
object Call_an_object_method extends App {
  val s = "Hello"
  val m = new MyClass()
  val n = new MyClass(3)

  println(HelloObject.s) // prints "Hello" by object getterHelloObject

  println(m.myMethod) // prints 0
  println(n.myMethod) // prints 3
}


  (define (withdraw amount)
    (if (>= balance amount)
        (begin (set! balance (- balance amount))
               balance)
        "Insufficient funds"))
  (define (deposit amount)
    (set! balance (+ balance amount))
    balance)
  (define (dispatch m)
    (cond ((eq? m 'withdraw) withdraw)
          ((eq? m 'deposit) deposit)
          (else (error "Unknown request -- MAKE-ACCOUNT"
                       m))))
  dispatch)


class MyClass(instance_var) {
    method add(num) {
        instance_var += num;
    }
}

var obj = MyClass(3);   # `instance_var` will be set to 3
obj.add(5);             # calls the add() method
say obj.instance_var;   # prints the value of `instance_var`: 8


BEGIN
    CLASS MyClass(instanceVariable);
    INTEGER instanceVariable;
    BEGIN
        PROCEDURE doMyMethod(n);
        INTEGER n;
        BEGIN
            Outint(instanceVariable, 5);
            Outtext(" + ");
            Outint(n, 5);
            Outtext(" = ");
            Outint(instanceVariable + n, 5);
            Outimage
        END;
    END;
    REF(MyClass) myObject;
    myObject :- NEW MyClass(5);
    myObject.doMyMethod(2)
END


prototypes define: #MyPrototype &parents: {Cloneable} &slots: #(instanceVar).
MyPrototype traits addSlot: #classVar.

[email protected](MyPrototype traits) new
[
  x clone `>> [instanceVar: 0. ]
].

[email protected](MyPrototype traits) someMethod
[
  x instanceVar = 1 /\ (x classVar = 3)
].


Object subclass: #MyClass
  instanceVariableNames: 'instanceVar'
  classVariableNames: 'classVar'
  poolDictionaries: ''
  category: 'Testing' !

!MyClass class methodsFor: 'instance creation'!
new
  ^self basicNew  instanceVar := 0 ! !

!MyClass methodsFor: 'testing'!
someMethod
  ^self instanceVar = 1; classVar = 3 ! !

MyClass new someMethod!


SpecialObject {

	classvar a = 42, <b = 0, <>c;    // Class variables. 42 and 0 are default values.
	var <>x, <>y;           // Instance variables.
	// Note: variables are private by default. In the above, "<" creates a getter, ">" creates a setter

	*new { |value|
		^super.new.init(value)       // constructor is a class method. typically calls some instance method to set up, here "init"
	}

	init { |value|
		x = value;
		y = sqrt(squared(a) + squared(b))
	}

	// a class method
	*randomizeAll {
		a = 42.rand;
		b = 42.rand;
		c = 42.rannd;
	}

	// an instance method
	coordinates {
		^Point(x, y) // The "^" means to return the result. If not specified, then the object itself will be returned ("^this")
	}

}


class MyClass{

  // stored property
  var variable : Int

  /**
  * The constructor
  */
  init() {
    self.variable = 42
  }

  /**
  * A method
  */
  func someMethod() {
    self.variable = 1
  }
}


package require TclOO
oo::class create summation {
    variable v
    constructor {} {
        set v 0
    }
    method add x {
        incr v $x
    }
    method value {} {
        return $v
    }
    destructor {
        puts "Ended with value $v"
    }
}
set sum [summation new]
puts "Start with [$sum value]"
for {set i 1} {$i <= 10} {incr i} {
    puts "Add $i to get [$sum add $i]"
}
$sum destroy


class Car
{
  //Constructor function.
  function this(brand, weight, price = 0) {
    this.brand = brand;
    this.weight = weight || 1000; // Resort to default value (with 'or' notation).
    this._price = price;
  }
  property price(v) // computable property, special kind of member function
  {
    get { return this._price; } // getter section
    set { this._price = v; }    // setter section
  }
  function toString() { // member function, method of a Car.
    return String.printf("<%s>",this.brand);
  }
}

class Truck : Car
{
  function this(brand, size) {
    super(brand, 2000); // Call of constructor of super class (Car here)
    this.size = size; // Custom property for just this object.
  }
}

var cars = [ // Some example car objects.
  new Car("Mazda"),
  new Truck("Volvo", 2, 30000)
];
for (var (i,car) in cars) // TIScript allows enumerate indexes and values
{
  stdout.printf("#%d %s $%d %v %v, %v %v", i, car.brand, car.price, car.weight, car.size,
                 car instanceof Car, car instanceof Truck);
}


#lang transd

class Point : {
    x: Double(),
    y: Double(),
    @init: (λ v Vector<Double>() (= x (get v 0)) (= y (get v 1))),
    print: (λ (textout "Point(" x "; " y ")\n" ))
}

MainModule: {
    v_: [[1.0, 2.0], [3.0, 4.0]],

    _start: (λ
	// creating an instance of class
    	(with pt Point([5.0, 6.0])
	  // calling a class' method
	  (print pt)
	)

	// creating several instances using data deserialization
        (with v Vector<Point>(v_)
          (for p in v do (print p))
    )   )
}


(defstruct shape ()
  cached-area

  (:init (self)
    (put-line `@self is born!`))

  (:fini (self)
    (put-line `@self says goodbye!`))

  (:method area (self)
    (or self.cached-area
        (set self.cached-area self.(calc-area)))))

(defstruct circle shape
  (radius 1.0)

  (:method calc-area (self)
    (* %pi% self.radius self.radius)))

(defstruct square shape
  (length 1.0)

  (:method calc-area (self)
    (* self.length self.length)))


typeset -T Summation_t=(
    integer sum

    # the constructor
    function create {
        _.sum=0
    }

    # a method
    function add {
        (( _.sum += $1 ))
    }
)

Summation_t s
for i in 1 2 3 4 5; do
    s.add $i
done
print ${s.sum}


public class MyClass : Object {
    // Instance variable
    public int variable;

    // Method
    public void some_method() {
        variable = 24;
    }

    // Constructor
    public MyClass() {
        variable = 42;
    }
}
void main() {
    // Class instance
    MyClass instance = new MyClass();
    print("%d\n", instance.variable);
    instance.some_method();
    print("%d\n", instance.variable);
    instance.variable = 84;
    print("%d\n", instance.variable);
}


Private Const m_default = 10
Private m_bar As Integer

Private Sub Class_Initialize()
  'constructor, can be used to set default values
  m_bar = m_default
End Sub

Private Sub Class_Terminate()
  'destructor, can be used to do some cleaning up
  'here we just print a message
  Debug.Print "---object destroyed---"
End Sub
Property Let Bar(value As Integer)
  m_bar = value
End Property

Property Get Bar() As Integer
  Bar = m_bar
End Property

Function DoubleBar()
  m_bar = m_bar * 2
End Function

Function MultiplyBar(x As Integer)
  'another method
  MultiplyBar = m_bar * x
  'Note: instead of using the instance variable m_bar we could refer to the Bar property of this object using the special word "Me":
  '  MultiplyBar = Me.Bar * x
End Function


Class Foo
   Private m_Bar As Integer

   Public Sub New()

   End Sub

   Public Sub New(ByVal bar As Integer)
       m_Bar = bar
   End Sub

   Public Property Bar() As Integer
       Get
           Return m_Bar
       End Get
       Set(ByVal value As Integer)
           m_Bar = value
       End Set
   End Property

   Public Sub DoubleBar()
       m_Bar *= 2
   End Sub

   Public Function MultiplyBar(ByVal x As Integer) As Integer
       Return x * Bar
   End Function

End Class


LOCAL o1 As MyClass, o2 As MyClass
*!* Instantiate o1
o1 = NEWOBJECT("MyClass")
o1.ShowInstance()
*!* Instantiate o2
o2 = CREATEOBJECT("MyClass", 2)
o2.ShowInstance()

DEFINE CLASS MyClass As Session
*!* Custom property (protected)
PROTECTED nInstance
nInstance = 0

*!* Constructor
PROCEDURE Init(tnInstance As Integer)
IF VARTYPE(tnInstance) = "N"
    THIS.nInstance = tnInstance
ELSE
    THIS.nInstance = THIS.nInstance + 1
ENDIF
ENDPROC

*!* Custom Method
PROCEDURE ShowInstance
? "Instance", THIS.nInstance
ENDPROC
ENDDEFINE


class Bear {
    // Constructs a Bear instance passing it a name
    // which is stored in the field _name
    // automatically created by Wren.
    construct new(name) { _name = name }

    // Property to get the name
    name { _name }

    // Method to make a noise.
    makeNoise() { System.print("Growl!") }
}

// Create a new Bear instance and assign a reference to it
// to the variable b.
var b = Bear.new("Bruno")

// Print the bear's name.
System.print("The bear is called %(b.name).")
// Make a noise.
b.makeNoise()