' FB 1.05.0 Win64

Type Closure
  Private:
    index As Integer
  Public:
    Declare Constructor(index As Integer = 0)
    Declare Function Square As Integer
End Type

Constructor Closure(index As Integer = 0)
   This.index = index
End Constructor

Function Closure.Square As Integer
   Return index * index
End Function

Dim a(1 To 10) As Closure

' create Closure objects which capture their index
For i As Integer = 1 To 10
  a(i) = Closure(i)
Next

' call the Square method on all but the last object
For i As Integer = 1 to 9
  Print a(i).Square
Next

Print
Print "Press any key to quit"
Sleep


package main

import "fmt"

func main() {
    fs := make([]func() int, 10)
    for i := range fs {
        i := i
        fs[i] = func() int {
            return i * i
        }
    }
    fmt.Println("func #0:", fs[0]())
    fmt.Println("func #3:", fs[3]())
}


def closures = (0..9).collect{ i -> { -> i*i } }


procedure main(args)                                      # Closure/Variable Capture
    every put(L := [], vcapture(1 to 10))                 # build list of index closures
    write("Randomly selecting L[",i := ?*L,"] = ",L[i]()) # L[i]() calls the closure
end

# The anonymous 'function', as a co-expression.  Most of the code is standard
# boilerplate needed to use a co-expression as an anonymous function.

procedure vcapture(x)             # vcapture closes over its argument
   return makeProc { repeat { (x[1]^2) @ &source } }
end

procedure makeProc(A)             # the makeProc PDCO from the UniLib Utils package
    return (@A[1], A[1])
end


blist := list(0,1,2,3,4,5,6,7,8,9) map(i,block(i,block(i*i)) call(i))
writeln(blist at(3) call)  // prints 9


import java.util.function.Supplier;
import java.util.ArrayList;

public class ValueCapture {
    public static void main(String[] args) {
	ArrayList<Supplier<Integer>> funcs = new ArrayList<>();
	for (int i = 0; i < 10; i++) {
	    int j = i;
	    funcs.add(() -> j * j);
	}

	Supplier<Integer> foo = funcs.get(3);
	System.out.println(foo.get()); // prints "9"
    }
}


var funcs = [];
for (var i = 0; i < 10; i++) {
    funcs.push( (function(i) {
                     return function() { return i * i; }
                })(i) );
}
window.alert(funcs[3]()); // alerts "9"


// version 1.0.6

fun main(args: Array<String>) {
    // create an array of 10 anonymous functions which return the square of their index
    val funcs = Array(10){ fun(): Int = it * it }
    // call all but the last
    (0 .. 8).forEach { println(funcs[it]()) }
}


{def A
 {A.new
  {S.map {lambda {:x} {* :x :x}}
         {S.serie 0 10}
}}}

{A.get 3 {A}}    // equivalent to A[3]
-> 9
{A.get 4 {A}}
-> 16


functions := 10 times to (Array) map {
  takes '[i].
  proc { (i) * (i). }.
}.

functions visit { println: $1 call. }.


> (set funcs (list-comp ((<- m (lists:seq 1 10)))
                      (lambda () (math:pow m 2))))


-- parent script "CallFunction"

property _code

-- if the function is supposed to return something, the code must contain a line that starts with "res="
on new (me, code)
  me._code = code
  return me
end

on call (me)
  ----------------------------------------
  -- If custom arguments were passed, evaluate them in the current context.
  -- Note: in the code passed to the constructor they have to be referenced
  -- as arg[1], arg[2], ...
  arg = []
  repeat with i = 3 to the paramCount
    arg[i-2] = param(i)
  end repeat
  ----------------------------------------
  res = VOID
  do(me._code)
  return res
end


:- object(value_capture).

    :- public(show/0).
    show :-
        integer::sequence(1, 10, List),
        meta::map(create_closure, List, Closures),
        meta::map(call_closure, List, Closures).

    create_closure(Index, [Double]>>(Double is Index*Index)).

    call_closure(Index, Closure) :-
        call(Closure, Result),
        write('Closure '), write(Index), write(' : '), write(Result), nl.

:- end_object.


funcs={}
for i=1,10 do
    table.insert(funcs, function() return i*i end)
end
funcs[2]()
funcs[3]()


Dim Base 0, A(10)
For i=0 to 9 {
      a(i)=lambda i -> i**2
}
For i=0 to 9 {
      Print a(i)()
}


using System.Console;

module Closures
{
    Main() : void
    {
        def f(x) { fun() { x ** 2 } }
        def funcs = $[f(x) | x in $[0 .. 10]].ToArray(); // using array for easy indexing

        WriteLine($"$(funcs[4]())");
        WriteLine($"$(funcs[2]())");
    }
}


var funcs: seq[proc(): int] = @[]

for i in 0..9:
  (proc =
    let x = i
    funcs.add(proc (): int = x * x))()

for i in 0..8:
  echo "func[", i, "]: ", funcs[i]()


use Collection.Generic;

class Capture {
  function : Main(args : String[]) ~ Nil {
     funcs := Vector->New()<FuncHolder<IntHolder> >;

     for(i := 0; i < 10; i += 1;) {
       funcs->AddBack(FuncHolder->New(\() ~ IntHolder : () => i * i)<IntHolder>);
     };

     each(i : funcs) {
       func := funcs->Get(i)->Get()<IntHolder>;
       func()->Get()->PrintLine();
     };
  }
}


NSMutableArray *funcs = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
  [funcs addObject:[^ { return i * i; } copy]];
}

int (^foo)(void) = funcs[3];
NSLog(@"%d", foo()); // logs "9"


let () =
  let cls = Array.init 10 (fun i -> (function () -> i * i)) in
  Random.self_init ();
  for i = 1 to 6 do
    let x = Random.int 9 in
    Printf.printf " fun.(%d) = %d\n" x (cls.(x) ());
  done


: newClosure(i)  #[ i sq ] ;
10 seq map(#newClosure) at(7) perform .


my @f = map(sub { $_ * $_ }, 0 .. 9);   # @f is an array of subs
print $f[$_](), "\n" for (0 .. 8); # call and print all but last


with javascript_semantics
-- First some generic handling stuff, handles partial_args
-- of any mixture of any length and element types.
sequence closures = {}
function add_closure(integer rid, sequence partial_args)
    closures = append(closures,{rid,partial_args})
    return length(closures) -- (return an integer id)
end function

function call_closure(integer id, sequence args)
    {integer rid, sequence partial_args} = closures[id]
    return call_func(rid,partial_args&args)
end function

-- The test routine to be made into a closure, or ten
-- Note that all external references/captured variables must
-- be passed as arguments, and grouped together on the lhs
function square(integer i)
    return i*i
end function

-- Create the ten closures as asked for.
-- Here, cids is just {1,2,3,4,5,6,7,8,9,10}, however ids would be more
-- useful for a mixed bag of closures, possibly stored all over the shop.
-- Likewise add_closure could have been a procedure for this demo, but
-- you would probably want the function in a real-world application.
sequence cids = {}
for i=1 to 10 do
--for i=11 to 20 do -- alternative test
    cids &= add_closure(routine_id("square"),{i})
end for
-- And finally call em (this loop is blissfully unaware what function
-- it is actually calling, and what partial_arguments it is passing)
for i=1 to 10 do
    printf(1," %d",call_closure(cids[i],{}))
end for


def power2
    dup *
enddef

getid power2 10 repeat

len for
    dup rot swap get rot swap exec print " " print
endfor

nl

/# Another mode #/
len for
    var i
    i get i swap exec print " " print
endfor


<?php
$funcs = array();
for ($i = 0; $i < 10; $i++) {
    $funcs[] = function () use ($i) { return $i * $i; };
}
echo $funcs[3](), "\n"; // prints 9
?>


(setq FunList
   (make
      (for @N 10
         (link (curry (@N) () (* @N @N))) ) ) )


array funcs = ({});
foreach(enumerate(10);; int i)
{
  funcs+= ({
              lambda(int j)
              {
                  return lambda()
                         {
                             return j*j;
                         };
              }(i)
          });
}


function Get-Closure ([double]$Number)
{
    {param([double]$Sum) return $script:Number *= $Sum}.GetNewClosure()
}


:-use_module(library(lambda)).

closure :-
	numlist(1,10, Lnum),
	maplist(make_func, Lnum, Lfunc),
	maplist(call_func, Lnum, Lfunc).

make_func(I, \X^(X is I*I)).

call_func(N, F) :-
	call(F, R),
	format('Func ~w : ~w~n', [N, R]).


funcs = []
for i in range(10):
    funcs.append(lambda: i * i)
print funcs[3]() # prints 81


  [ table ] is functions ( n --> [ )

  10 times
    [ i^ ' [ dup * ] join
      ' functions put ]

  5 functions do echo


# assign 's' a list of ten functions
s <- sapply (1:10,  # integers 1..10 become argument 'x' below
    function (x) {
        x  # force evaluation of promise x
	function (i=x) i*i   # this *function* is the return value
    })

s[[5]]()  # call the fifth function in the list of returned functions
[1] 25    # returns vector of length 1 with the value 25


#lang racket
(define functions (for/list ([i 10]) (λ() (* i i))))
(map (λ(f) (f)) functions)


my @c = gather for ^10 -> $i {
    take { $i * $i }
}

.().say for @c.pick(*);  # call them in random order


funs: collect [repeat i 10 [keep func [] reduce [i ** 2]]]

>> funs/7
== 49


/*REXX program has a list of ten functions, each returns its invocation (index) squared.*/
parse arg seed base $                            /*obtain optional arguments from the CL*/
if datatype(seed, 'W')  then call random ,,seed  /*Not given?  Use random  start seed.  */
if base=='' | base=","  then base=0              /* "    "     Use a zero─based list.   */
if $=''  then $= 8 5 4 9 1 3 2 7 6 0             /* "    "     Use ordered function list*/
                                                 /*the $ list must contain 10 functions.*/
say 'the' word("zero one", base+1)'─based list is: '   $       /*show list of functions.*/
                                                 /*BASED  must be either   1   or   0.  */
?='.'random(0, 9)                                /*get a random name of a function.     */
interpret  'CALL'  ?                             /*invoke a randomly selected function. */
say 'function '    ?     " returned "    result  /*display the value of random function.*/
exit                                             /*stick a fork in it,  we're all done. */
/*────────────────────────[Below are the closest things to anonymous functions in REXX].*/
.0: return  .(0)                                 /*function  .0   ─── bump its counter. */
.1: return  .(1)                                 /*    '     .1    "    "   "     "     */
.2: return  .(2)                                 /*    '     .2    "    "   "     "     */
.3: return  .(3)                                 /*    '     .3    "    "   "     "     */
.4: return  .(4)                                 /*    '     .4    "    "   "     "     */
.5: return  .(5)                                 /*    '     .5    "    "   "     "     */
.6: return  .(6)                                 /*    '     .6    "    "   "     "     */
.7: return  .(7)                                 /*    '     .7    "    "   "     "     */
.8: return  .(8)                                 /*    '     .8    "    "   "     "     */
.9: return  .(9)                                 /*    '     .9    "    "   "     "     */
/*──────────────────────────────────────────────────────────────────────────────────────*/
.:  arg #;  _=wordpos(#,$); if _==0  then return 'not in the list.'; return (_-(\base))**2


x = funcs(7)
see x + nl

func funcs n
     fn = list(n)
     for i = 1 to n
         fn[i] =i*i
     next
     return fn


procs = Array.new(10){|i| ->{i*i} } # -> creates a lambda
p procs[7].call # => 49


val closures=for(i <- 0 to 9) yield (()=>i*i)
0 to 8 foreach (i=> println(closures(i)()))
println("---\n"+closures(7)())


;;; Collecting lambdas in a tail-recursive function.
(define (build-list-of-functions n i list)
  (if (< i n)
      (build-list-of-functions n (+ i 1) (cons (lambda () (* (- n i) (- n i))) list))
      list))

(define list-of-functions (build-list-of-functions 10 1 '()))

(map (lambda (f) (f)) list-of-functions)

((list-ref list-of-functions 8))


var f = (
    10.of {|i| func(j){i * j} }
)

9.times { |j|
    say f[j](j)
}


funcs := (1 to: 10) collect: [ :i | [ i * i ] ] .
(funcs at: 3) value displayNl .


var fnlist = {};
for var i = 0; i < 10; i++ {
	fnlist[i] = function() {
		return i * i;
	};
}

print(fnlist[3]()); // prints 9
print(fnlist[5]()); // prints 25


List.map (fn x => x () )  ( List.tabulate (10,(fn i => (fn  ()=> i*i)) ) ) ;


var funcs: [() -> Int] = []
for var i = 0; i < 10; i++ {
  funcs.append({ i * i })
}
println(funcs[3]()) // prints 100


package require Tcl 8.6; # Just for tailcall command
# Builds a value-capturing closure; does NOT couple variables
proc closure {script} {
    set valuemap {}
    foreach v [uplevel 1 {info vars}] {
	lappend valuemap [list $v [uplevel 1 [list set $v]]]
    }
    set body [list $valuemap $script [uplevel 1 {namespace current}]]
    # Wrap, to stop untoward argument passing
    return [list apply [list {} [list tailcall apply $body]]]
    # A version of the previous line compatible with Tcl 8.5 would be this
    # code, but the closure generated is more fragile:
    ### return [list apply $body]
}

# Simple helper, to avoid capturing unwanted variable
proc collectFor {var from to body} {
    upvar 1 $var v
    set result {}
    for {set v $from} {$v < $to} {incr v} {lappend result [uplevel 1 $body]}
    return $result
}
# Build a list of closures
proc buildList {} {
    collectFor i 0 10 {
	closure {
	    # This is the body of the closure
	    return [expr $i*$i]
	}
    }
}
set theClosures [buildList]
foreach i {a b c d e} {# Do 5 times; demonstrates no variable leakage
    set idx [expr {int(rand()*9)}]; # pick random int from [0..9)
    puts $idx=>[{*}[lindex $theClosures $idx]]
}


(let ((funs (mapcar (ret (op * @@1 @@1)) (range 1 10))))
  [mapcar call [funs 0..-1]])


var fs = List.filled(10, null)
for (i in 0...fs.count) {
    fs[i] = Fn.new { i * i }
}

for (i in 0...fs.count-1) System.print("Function #%(i):  %(fs[i].call())")


dim funcs$(10)

sub power2(i)
    return i * i
end sub

for i = 1 to 10
    funcs$(i) = "power2"
next

for i = 1 to 10
    print execute(funcs$(i), i)
next


(0).pump(10,List,fcn(i){i*i}.fp)[8]() //-->64
list:=(0).pump(10,List,fcn(i){i*i}.fp);
foreach n in (list.len()-1) { list[n]().println() }
list.run(True).println()


T MyType
   Int public_variable // member variable = instance variable
   . Int private_variable

   F () // constructor
      .private_variable = 0

   F someMethod() // member function = method
      .private_variable = 1
      .public_variable = 10


package {
    public class MyClass {

        private var myVariable:int;  // Note: instance variables are usually "private"

        /**
         * The constructor
         */
        public function MyClass() {
            // creates a new instance
        }

        /**
         * A method
         */
        public function someMethod():void {
            this.myVariable = 1; // Note: "this." is optional
            // myVariable = 1; works also
        }
    }
}


package My_Package is
   type My_Type is tagged private;
   procedure Some_Procedure(Item : out My_Type);
    function Set(Value : in Integer) return My_Type;
private
   type My_Type is tagged record
      Variable : Integer := -12;
   end record;
end My_Package;


class Circle (radius, x, y) extends  Shape (x, y) implements Drawable {
    var myvec = new Vector (x, y)

    public function draw() {
        // draw the circle
    }
}


MODE MYDATA = STRUCT(
    INT name1
);
STRUCT(
    INT name2,
    PROC (REF MYDATA)REF MYDATA new,
    PROC (REF MYDATA)VOID init,
    PROC (REF MYDATA)VOID some method
) class my data;
class my data := (
  # name2 := # 2, # Class attribute #

  # PROC new := # (REF MYDATA new)REF MYDATA:(
        (init OF class my data)(new);
        new
   ),

  # PROC init := # (REF MYDATA self)VOID:(
        """ Constructor  (Technically an initializer rather than a true 'constructor') """;
        name1 OF self := 0 # Instance attribute #
    ),

  # PROC some method := # (REF MYDATA self)VOID:(
        """ Method """;
        name1 OF self := 1;
        name2 OF class my data := 3
    )
);

# class name, invoked as a function is the constructor syntax #
REF MYDATA my data = (new OF class my data)(LOC MYDATA);

MODE GENDEROPT = UNION(STRING, VOID);
MODE AGEOPT = UNION(INT, VOID);

MODE MYOTHERDATA = STRUCT(
    STRING name,
    GENDEROPT gender,
    AGEOPT age
);
STRUCT (
    INT count,
    PROC (REF MYOTHERDATA, STRING, GENDEROPT, AGEOPT)REF MYOTHERDATA new,
    PROC (REF MYOTHERDATA, STRING, GENDEROPT, AGEOPT)VOID init,
    PROC (REF MYOTHERDATA)VOID del
) class my other data;
class my other data := (
  # count := # 0,  # Population of "(init OF class my other data)" objects #
# PROC new := # (REF MYOTHERDATA new, STRING name, GENDEROPT gender, AGEOPT age)REF MYOTHERDATA:(
          (init OF class my other data)(new, name, gender, age);
          new
      ),

  # PROC init := # (REF MYOTHERDATA self, STRING name, GENDEROPT gender, AGEOPT age)VOID:(
        """ One initializer required, others are optional (with different defaults) """;
        count OF class my other data +:= 1;
        name OF self := name;
        gender OF self := gender;
        CASE gender OF self IN
            (VOID):gender OF self := "Male"
        ESAC;
        age OF self := age
    ),

  # PROC del := # (REF MYOTHERDATA self)VOID:(
        count OF class my other data -:= 1
    )
);

PROC attribute error := STRING: error char; # mend the error with the "error char" #

# Allocate the instance from HEAP #
REF MYOTHERDATA person1 =  (new OF class my other data)(HEAP MYOTHERDATA, "John", EMPTY, EMPTY);
print (((name OF person1), ": ",
        (gender OF person1|(STRING gender):gender|attribute error), " "));  # "John Male" #
print (((age OF person1|(INT age):age|attribute error), new line)); # Raises AttributeError exception! #

# Allocate the instance from LOC (stack) #
REF MYOTHERDATA person2 = (new OF class my other data)(LOC MYOTHERDATA, "Jane", "Female", 23);
print (((name OF person2), ": ",
        (gender OF person2|(STRING gender):gender|attribute error), " "));
print (((age OF person2|(INT age):age|attribute error), new line))  # "Jane Female 23" #


OBJECT a_class
  varA, varP
ENDOBJECT

-> this could be used like a constructor
PROC init() OF a_class
  self.varP := 10
  self.varA := 2
ENDPROC

-> the special proc end() is for destructor
PROC end() OF a_class
-> nothing to do here...
ENDPROC

-> a not so useful getter
PROC getP() OF a_class IS self.varP

PROC main()
  DEF obj : PTR TO a_class
  NEW obj.init()
  WriteF('\d\n', obj.varA)   -> this can be done, while
                             -> varP can't be accessed directly
  WriteF('\d\n', obj.varP)   -> or
  WriteF('\d\n', obj.getP())
  END obj
ENDPROC


obj := new MyClass
obj.WhenCreated()

class MyClass {
; Instance Variable #1
   time := A_Hour ":" A_Min ":" A_Sec

; Constructor
   __New() {
      MsgBox, % "Constructing new object of type: " this.__Class
      FormatTime, date, , MM/dd/yyyy
   ; Instance Variable #2
      this.date := date
   }
; Method
   WhenCreated() {
      MsgBox, % "Object created at " this.time " on " this.date
   }
}


PRAGMA COMPILER g++
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive

OPTION PARSE FALSE

'---The class does the declaring for you

CLASS Books
	public:
		const char* title;
		const char* author;
		const char* subject;
		int book_id;
END CLASS

'---pointer to an object declaration (we use a class called Books)
DECLARE Book1 TYPE Books
'--- the correct syntax for class
Book1  =  Books()

'--- initialize the strings const char* in c++
Book1.title = "C++ Programming to bacon "
Book1.author = "anyone"
Book1.subject ="RECORD Tutorial"
Book1.book_id = 1234567

PRINT "Book title   : " ,Book1.title FORMAT "%s%s\n"
PRINT "Book author  : ", Book1.author FORMAT "%s%s\n"
PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n"
PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"


  DECLARE SUB MyClassDelete (pthis AS MyClass)
  DECLARE SUB MyClassSomeMethod (pthis AS MyClass)
  DECLARE SUB MyClassInit (pthis AS MyClass)

  TYPE MyClass
    Variable AS INTEGER
  END TYPE

  DIM obj AS MyClass
  MyClassInit obj
  MyClassSomeMethod obj

  SUB MyClassInit (pthis AS MyClass)
    pthis.Variable = 0
  END SUB

  SUB MyClassSomeMethod (pthis AS MyClass)
    pthis.Variable = 1
  END SUB


      INSTALL @lib$+"CLASSLIB"

      REM Declare the class:
      DIM MyClass{variable, @constructor, _method}
      DEF [email protected] MyClass.variable = PI : ENDPROC
      DEF MyClass._method = MyClass.variable ^ 2

      REM Register the class:
      PROC_class(MyClass{})

      REM Instantiate the class:
      PROC_new(myclass{}, MyClass{})

      REM Call the method:
      PRINT FN(myclass._method)

      REM Discard the instance:
      PROC_discard(myclass{})


ExClass ← {
  𝕊 value: # Constructor portion
  priv ← value
  priv2 ⇐ 0
  ChangePriv ⇐ { priv ↩ 𝕩 }
  DispPriv ⇐ {𝕊: •Show priv‿priv2 }

}

obj ← ExClass 5
[email protected]
obj.ChangePriv 6
[email protected]


# Constructors can take parameters (that automatically become properties)
constructor Ball(color, radius)

	# Objects can also have functions (closures)
	:volume
		return 4/3 * {pi} * (radius ** 3)
	end
	:show
		return "a " + color + " ball with radius " + radius
	end

end

red_ball = Ball("red", 2)
print(red_ball)
# => a red ball with radius 2


( ( resolution
  =   (x=)
      (y=)
      (new=.!arg:(?(its.x),?(its.y)))
  )
& new$(resolution,640,480):?VGA
& new$(resolution,1920,1080):?1080p
& out$("VGA: horizontal " !(VGA..x) " vertical " !(VGA..y)));


#include <stdlib.h>

typedef struct sMyClass
{
  int variable;
} *MyClass;

MyClass  MyClass_new()
{
  MyClass pthis = malloc(sizeof *pthis);
  pthis->variable = 0;
  return pthis;
}

void MyClass_delete(MyClass* pthis)
{
  if (pthis)
  {
    free(*pthis);
    *pthis = NULL;
  }
}

void MyClass_someMethod(MyClass pthis)
{
  pthis->variable = 1;
}

MyClass obj = MyClass_new();
MyClass_someMethod(obj);
MyClass_delete(&obj);


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() );
    }
}


class MyClass
{
public:
  void someMethod(); // member function = method
  MyClass(); // constructor
private:
  int variable; // member variable = instance variable
};

// implementation of constructor
MyClass::MyClass():
  variable(0)
{
  // here could be more code
}

// implementation of member function
void MyClass::someMethod()
{
  variable = 1; // alternatively: this->variable = 1
}

// Create an instance as variable
MyClass instance;

// Create an instance on free store
MyClass* pInstance = new MyClass;
// Instances allocated with new must be explicitly destroyed when not needed any more:
delete pInstance;


; You can think of this as an interface
(defprotocol Foo (getFoo [this]))

; Generates Example1 Class with foo as field, with method that returns foo.
(defrecord Example1 [foo] Foo (getFoo [this] foo))

; Create instance and invoke our method to return field value
(-> (Example1. "Hi") .getFoo)
"Hi"


       IDENTIFICATION DIVISION.
       CLASS-ID. my-class INHERITS base.

       *> The 'INHERITS base' and the following ENVIRONMENT DIVISION
       *> are optional (in Visual COBOL).
       ENVIRONMENT DIVISION.
       CONFIGURATION SECTION.
       REPOSITORY.
           CLASS base.

           *> There is no way (as far as I can tell) of creating a
           *> constructor. However, you could wrap it with another
           *> method to achieve the desired effect.
           *>...

           OBJECT.
               *> Instance data
               DATA DIVISION.
               WORKING-STORAGE SECTION.
               01  instance-variable PIC 9(8).

               *> Properties can have getters and setters automatically
               *> generated.
               01  a-property        PIC 9(8) PROPERTY.

               PROCEDURE DIVISION.

               METHOD-ID. some-method.
               PROCEDURE DIVISION.
                   *> ...
               END METHOD some-method.
           END OBJECT.
       END CLASS my-class.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. example-class-use.

       ENVIRONMENT DIVISION.
       CONFIGURATION SECTION.
       REPOSITORY.
           *> These declarations brings the class and property into
           *> scope.
           CLASS my-class
           PROPERTY a-property.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       *> Declaring a my-class reference variable.
       01  instance USAGE OBJECT REFERENCE my-class.

       PROCEDURE DIVISION.

           *> Invoking a static method or (in this case) a constructor.
           INVOKE my-class "new" RETURNING instance

           *> Invoking an instance method.
           INVOKE instance "some-method"

           *> Using the setter and getter of a-property.
           MOVE 5 TO a-property OF instance
           DISPLAY a-property OF instance

           GOBACK
           .

       END PROGRAM example-class-use.


class Rectangle
  # The constructor is defined as a bare function. This
  # constructor accepts one argument and automatically assigns it
  # to an instance variable.
  (@width) ->

  # Another instance variable.
  length: 10

  # A method.
  area: ->
    @width * @length

# Instantiate the class using the 'new' operator.
rect = new Rectangle 2


# Create a basic class
class Rectangle
  # Constructor that accepts one argument
  constructor: (@width) ->

  # An instance variable
  length: 10

  # A method
  area: () ->
    @width * @length

# Instantiate the class using the new operator
rect = new Rectangle 2


(defclass circle ()
  ((radius :initarg :radius
           :initform 1.0
           :type number
           :reader radius)))

(defmethod area ((shape circle))
  (* pi (expt (radius shape) 2)))

> (defvar *c* (make-instance 'circle :radius 2))
> (area *c*)
12.566370614359172d0


MODULE Point;
IMPORT
	Strings;
TYPE
	Instance* = POINTER TO LIMITED RECORD
		x-, y- : LONGINT; (* Instance variables *)
	END;

	PROCEDURE (self: Instance) Initialize*(x,y: LONGINT), NEW;
	BEGIN
		self.x := x;
		self.y := y
	END Initialize;

	(* constructor *)
	PROCEDURE New*(x, y: LONGINT): Instance;
	VAR
		point: Instance;
	BEGIN
		NEW(point);
		point.Initialize(x,y);
		RETURN point
	END New;

	(* methods *)
	PROCEDURE (self: Instance) Add*(other: Instance): Instance, NEW;
	BEGIN
		RETURN New(self.x + other.x,self.y + other.y);
	END Add;

	PROCEDURE (self: Instance) ToString*(): POINTER TO ARRAY OF CHAR, NEW;
	VAR
		xStr,yStr: ARRAY 64 OF CHAR;
		str: POINTER TO ARRAY OF CHAR;
	BEGIN
		Strings.IntToString(self.x,xStr);
		Strings.IntToString(self.y,yStr);
		NEW(str,128);str^ := "@(" +xStr$ + "," + yStr$ + ")";
		RETURN str
	END ToString;
END Point.


class MyClass

  def initialize
    @instance_var = 0
  end

  def add_1
    @instance_var += 1
  end

end

my_class = MyClass.new


import std.stdio;

class MyClass {
    //constructor (not necessary if empty)
    this() {}

    void someMethod() {
        variable = 1;
    }

    // getter method
    @property int variable() const {
        return variable_;
    }

    // setter method
    @property int variable(int newVariable) {
        return variable_ = newVariable;
    }

    private int variable_;
}

void main() {
    // On default class instances are allocated on the heap
    // The GC will manage their lifetime
    auto obj = new MyClass();

    // prints 'variable = 0', ints are initialized to 0 by default
    writeln("variable = ", obj.variable);

    // invoke the method
    obj.someMethod();

    // prints 'variable = 1'
    writeln("variable = ", obj.variable);

    // set the variable using setter method
    obj.variable = 99;

    // prints 'variable = 99'
    writeln("variable = ", obj.variable);
}


program SampleClass;

{$APPTYPE CONSOLE}

type
  TMyClass = class
  private
    FSomeField: Integer; // by convention, fields are usually private and exposed as properties
  public
    constructor Create;
    destructor Destroy; override;
    procedure SomeMethod;
    property SomeField: Integer read FSomeField write FSomeField;
  end;

constructor TMyClass.Create;
begin
  FSomeField := -1
end;

destructor TMyClass.Destroy;
begin
  // free resources, etc

  inherited Destroy;
end;

procedure TMyClass.SomeMethod;
begin
  // do something
end;

var
  lMyClass: TMyClass;
begin
  lMyClass := TMyClass.Create;
  try
    lMyClass.SomeField := 99;
    lMyClass.SomeMethod();
  finally
    lMyClass.Free;
  end;
end.


type
  TMyClass = class
  private
    FSomeField: Integer; // by convention, fields are usually private and exposed as properties
  public
    constructor Create;
    begin
       FSomeField := -1;
    end;
    procedure SomeMethod;
    property SomeField: Integer read FSomeField write FSomeField;
  end;

procedure TMyClass.SomeMethod;
begin
  // do something
end;

var lMyClass: TMyClass;

lMyClass := new TMyClass; // can also use TMyClass.Create

lMyClass.SomeField := 99;
lMyClass.SomeMethod;


def makeColor(name :String) {
    def color {
        to colorize(thing :String) {
          return `$name $thing`
        }
    }
    return color
}


(lib 'gloops) ; load oo library

(define-class Person null (name (age :initform 66)))
(define-method tostring (Person) (lambda (p)  ( format "🚶 %a " p.name)))
(define-method mailto (Person Person) (lambda( p o) (printf "From %a to  %a : ..." p o)))

;; define a sub-class of Person with same methods
(define-class Writer (Person)  (books))
(define-method tostring (Writer) (lambda (w)( format "🎩 %a" w.name)))
(define-method mailto (Person Writer)
	(lambda (p w) (printf " From %a (age %d). Dear writer of %a ..." p p.age  w.books )))


import extensions;

class MyClass
{
    prop int Variable;

    someMethod()
    {
        Variable := 1
    }

    constructor()
    {
    }
}

public program()
{
    // instantiate the class
    var instance := new MyClass();

    // invoke the method
    instance.someMethod();

    // get the variable
    console.printLine("Variable=",instance.Variable)
}


PROGRAM CLASS2_DEMO

CLASS QUADRATO

    LOCAL LATO

    PROCEDURE GETLATO(L)
       LATO=L
    END PROCEDURE

    PROCEDURE AREA(->A)
       A=LATO*LATO
    END PROCEDURE

    PROCEDURE PERIMETRO(->P)
       P=4*LATO
    END PROCEDURE

END CLASS

NEW P:QUADRATO,Q:QUADRATO

BEGIN
    P_GETLATO(10)
    P_AREA(->AREAP)
    PRINT(AREAP)
    Q_GETLATO(20)
    Q_PERIMETRO(->PERIMETROQ)
    PRINT(PERIMETROQ)
END PROGRAM


type MyClass(init) =      // constructor with one argument: init
  let mutable var = init  // a private instance variable
  member x.Method() =     // a simple method
    var <- var + 1
    printfn "%d" var

// create an instance and use it
let myObject = new MyClass(42)
myObject.Method()


TUPLE: my-class foo bar baz ;
M: my-class quux foo>> 20 + ;
C: <my-class> my-class
10 20 30 <my-class> quux ! result: 30
TUPLE: my-child-class < my-class quxx ;
C: <my-child-class> my-child-class
M: my-child-class foobar 20 >>quux ;
20 20 30 <my-child-class> foobar quux ! result: 30


class class_name[ ( param_list ) ] [ from inh1[, inh2, ..., inhN] ]
    [ static block ]
    [ properties declaration ]
    [init block]
    [method list]
end


class MyClass {
  read_slot: 'instance_var # creates getter method for @instance_var
  @@class_var = []

  def initialize {
    # 'initialize' is the constructor method invoked during 'MyClass.new' by convention
    @instance_var = 0
  }

  def some_method {
    @instance_var = 1
    @another_instance_var = "foo"
  }

  # define class methods: define a singleton method on the class object
  def self class_method {
    # ...
  }

  # you can also name the class object itself
  def MyClass class_method {
    # ...
  }
}

myclass = MyClass new


class MyClass
{
  // an instance variable
  Int x

  // a constructor, providing default value for instance variable
  new make (Int x := 1)
  {
    this.x = x
  }

  // a method, return double the number x
  public Int double ()
  {
    return 2 * x
  }
}

class Main
{
  public static Void main ()
  {
    a := MyClass (2)  // instantiates the class, with x = 2
    b := MyClass()    // instantiates the class, x defaults to 1
    c := MyClass { x = 3 }  // instantiates the class, sets x to 3
  }
}


:class MyClass <super Object

  int memvar

  :m ClassInit: ( -- )
       ClassInit: super
       1 to memvar ;m

  :m ~: ( -- )  ." Final " show: [ Self ] ;m

  :m set: ( n -- )  to memvar ;m
  :m show: ( -- ) ." Memvar = " memvar . ;m

;class


!-----------------------------------------------------------------------
!Module accuracy defines precision and some constants
!-----------------------------------------------------------------------
module accuracy_module
   implicit none
   integer, parameter, public :: rdp = kind(1.d0)
   ! constants
   real(rdp), parameter :: pi=3.141592653589793238462643383279502884197_rdp
end module accuracy_module

!-----------------------------------------------------------------------
!Module typedefs_module contains abstract derived type and extended type definitions.
! Note that a reserved word "class" in Fortran is used to describe
! some polymorphic variable  whose data type may vary at run time.
!-----------------------------------------------------------------------
module typedefs_module
   use accuracy_module
   implicit none

   private ! all
   public :: TPoint, TShape, TCircle, TRectangle, TSquare ! public only these defined derived types

   ! abstract derived type
   type, abstract :: TShape
      real(rdp) :: area
      character(len=:),allocatable :: name
   contains
      ! deferred method i.e. abstract method =  must be overridden in extended type
      procedure(calculate_area), deferred,pass :: calculate_area
   end type TShape
   ! just declaration of the abstract method/procedure for TShape type
   abstract interface
      function  calculate_area(this)
         use accuracy_module
         import TShape !imports TShape type from host scoping unit and makes it accessible here
         implicit none
         class(TShape) :: this
         real(rdp) :: calculate_area

      end function calculate_area
   end interface

   ! auxiliary derived type
   type TPoint
      real(rdp) :: x,y
   end type TPoint

   ! extended derived type
   type, extends(TShape) :: TCircle
      real(rdp) :: radius
      real(rdp), private :: diameter
      type(TPoint) :: centre
   contains
      procedure, pass :: calculate_area => calculate_circle_area
      procedure, pass :: get_circle_diameter
      final :: finalize_circle
   end type TCircle

   ! extended derived type
   type, extends(TShape) :: TRectangle
      type(TPoint) :: A,B,C,D
   contains
      procedure, pass :: calculate_area => calculate_rectangle_area
      final :: finalize_rectangle
   end type TRectangle

   ! extended derived type
   type, extends(TRectangle) :: TSquare
   contains
      procedure, pass :: calculate_area => calculate_square_area
      final :: finalize_square
   end type TSquare

 contains

   ! finalization subroutines for each type
   ! They called recursively, i.e. finalize_rectangle
   ! will be called after finalize_square subroutine
   subroutine finalize_circle(x)
      type(TCircle), intent(inout) :: x
      write(*,*) "Deleting TCircle object"
   end subroutine finalize_circle

   subroutine finalize_rectangle(x)
      type(TRectangle), intent(inout) :: x
      write(*,*) "Deleting also TRectangle object"
   end subroutine finalize_rectangle

   subroutine finalize_square(x)
      type(TSquare), intent(inout) :: x
      write(*,*) "Deleting TSquare object"
   end subroutine finalize_square

   function calculate_circle_area(this)
      implicit none
      class(TCircle) :: this
      real(rdp) :: calculate_circle_area
      this%area = pi * this%radius**2
      calculate_circle_area = this%area
   end function calculate_circle_area

   function calculate_rectangle_area(this)
      implicit none
      class(TRectangle) :: this
      real(rdp) :: calculate_rectangle_area
      ! here could be more code
      this%area = 1
      calculate_rectangle_area = this%area
   end function calculate_rectangle_area

   function calculate_square_area(this)
      implicit none
      class(TSquare) :: this
      real(rdp) :: calculate_square_area
      ! here could be more code
      this%area = 1
      calculate_square_area = this%area
   end function calculate_square_area

   function  get_circle_diameter(this)
      implicit none
      class(TCircle) :: this
      real(rdp) :: get_circle_diameter
      this % diameter = 2.0_rdp * this % radius
      get_circle_diameter = this % diameter
   end function get_circle_diameter

end module typedefs_module

!-----------------------------------------------------------------------
!Main program
!-----------------------------------------------------------------------
program    rosetta_class
   use accuracy_module
   use typedefs_module
   implicit none

   ! we need this subroutine in order to show the finalization
   call test_types()

 contains

   subroutine test_types()
      implicit none
      ! declare object of type TPoint
      type(TPoint), target :: point
      ! declare object of type TCircle
      type(TCircle),target :: circle
      ! declare object of type TSquare
      type(TSquare),target :: square

      ! declare pointers
      class(TPoint), pointer :: ppo
      class(TCircle), pointer :: pci
      class(TSquare), pointer :: psq

      !constructor
      point = TPoint(5.d0,5.d0)
      ppo => point
      write(*,*) "x=",point%x,"y=",point%y

      pci => circle

      pci % radius = 1
      write(*,*) pci % radius
      ! write(*,*) pci % diameter !No,it is a PRIVATE component
      write(*,*) pci % get_circle_diameter()
      write(*,*) pci % calculate_area()
      write(*,*) pci % area

      psq => square

      write(*,*) psq % area
      write(*,*) psq % calculate_area()
      write(*,*) psq % area
   end subroutine test_types

end program rosetta_class


' FB 1.05.0 Win64

Type MyClass
  Private:
    myInt_ As Integer
  Public:
    Declare Constructor(myInt_ As Integer)
    Declare Property MyInt() As Integer
    Declare Function Treble() As Integer
End Type

Constructor MyClass(myInt_ As Integer)
   This.myInt_ = myInt_
End Constructor

Property MyClass.MyInt() As Integer
  Return myInt_
End Property

Function MyClass.Treble() As Integer
  Return 3 * myInt_
End Function

Dim mc As MyClass = MyClass(24)
Print mc.MyInt, mc.Treble()
Print "Press any key to quit the program"
Sleep


struct Rectangle{
    float width;
    float height;
};

Rectangle new(float width,float height){
    Rectangle self;
    self.width = width;
    self.height = height;
    return self;
}

float area(Rectangle self){
    return self.width*self.height;
}

float perimeter(Rectangle self){
    return (self.width+self.height)*2.0;
}


BEGIN # find circular primes - primes where all cyclic permutations  #
      # of the digits are also prime                                 #
    # genertes a sieve of circular primes, only the first            #
    # permutation of each prime is flagged as TRUE                   #
    OP   CIRCULARPRIMESIEVE = ( INT n )[]BOOL:
         BEGIN
            [ 0 : n ]BOOL prime;
            prime[ 0 ] := prime[ 1 ] := FALSE;
            prime[ 2 ] := TRUE;
            FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE  OD;
            FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD;
            FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB prime ) DO
                IF prime[ i ] THEN
                    FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD
                FI
            OD;
            INT first digit multiplier := 10;
            INT max with multiplier    := 99;
            # the 1 digit primes are non-curcular, so start at 10    #
            FOR i FROM 10 TO UPB prime DO
                IF i > max with multiplier THEN
                    # starting a new power of ten                    #
                    first digit multiplier *:= 10;
                    max with multiplier    *:= 10 +:= 9
                FI;
                IF prime[ i ] THEN
                    # have a prime #
                    # cycically permute the number until we get back #
                    # to the original - flag all the permutations    #
                    # except the original as non-prime               #
                    INT permutation := i;
                    WHILE permutation :=   ( permutation OVER 10 )
                                       + ( ( permutation MOD  10 ) * first digit multiplier )
                                       ;
                          permutation /= i
                    DO
                        IF NOT prime[ permutation ] THEN
                            # the permutation is not prime           #
                            prime[ i ] := FALSE
                        ELIF permutation > i THEN
                            # haven't permutated e.g. 101 to 11      #
                            IF NOT prime[ permutation ] THEN
                                # i is not a circular prime          #
                                prime[ i ] := FALSE
                            FI;
                            prime[ permutation ] := FALSE
                        FI
                    OD
                FI
            OD;
            prime
         END # CIRCULARPRIMESIEVE # ;
    # construct a sieve of circular primes up to 999 999              #
    # only the first permutation is included                          #
    []BOOL prime = CIRCULARPRIMESIEVE 999 999;
    # print the first 19 circular primes #
    INT c count := 0;
    print( ( "First 19 circular primes: " ) );
    FOR i WHILE c count < 19 DO
        IF prime[ i ] THEN
            print( ( " ", whole( i, 0 ) ) );
            c count +:= 1
        FI
    OD;
    print( ( newline ) )
END


package main

import "fmt"

// a basic "class."
// In quotes because Go does not use that term or have that exact concept.
// Go simply has types that can have methods.
type picnicBasket struct {
    nServings int // "instance variables"
    corkscrew bool
}

// a method (yes, Go uses the word method!)
func (b *picnicBasket) happy() bool {
    return b.nServings > 1 && b.corkscrew
}

// a "constructor."
// Also in quotes as Go does not have that exact mechanism as part of the
// language.  A common idiom however, is a function with the name new<Type>,
// that returns a new object of the type, fully initialized as needed and
// ready to use.  It makes sense to use this kind of constructor function when
// non-trivial initialization is needed.  In cases where the concise syntax
// shown is sufficient however, it is not idiomatic to define the function.
// Rather, code that needs a new object would simply contain &picnicBasket{...
func newPicnicBasket(nPeople int) *picnicBasket {
    // arbitrary code to interpret arguments, check resources, etc.
    // ...
    // return data new object.
    // this is the concise syntax.  there are other ways of doing it.
    return &picnicBasket{nPeople, nPeople > 0}
}

// how to instantiate it.
func main() {
    var pb picnicBasket          // create on stack (probably)
    pbl := picnicBasket{}        // equivalent to above
    pbp := &picnicBasket{}       // create on heap.  pbp is pointer to object.
    pbn := new(picnicBasket)     // equivalent to above
    forTwo := newPicnicBasket(2) // using constructor
    // equivalent to above.  field names, called keys, are optional.
    forToo := &picnicBasket{nServings: 2, corkscrew: true}

    fmt.Println(pb.nServings, pb.corkscrew)
    fmt.Println(pbl.nServings, pbl.corkscrew)
    fmt.Println(pbp)
    fmt.Println(pbn)
    fmt.Println(forTwo)
    fmt.Println(forToo)
}


/** Ye olde classe declaration */
class Stuff {
    /** Heare bee anne instance variable declared */
    def guts

    /** This constructor converts bits into Stuff */
    Stuff(injectedGuts) {
        guts = injectedGuts
    }

    /** Brethren and sistren, let us flangulate with this fine flangulating method */
    def flangulate() {
        println "This stuff is flangulating its guts: ${guts}"
    }
}


begin % find circular primes - primes where all cyclic permutations  %
      % of the digits are also prime                                 %
    % sets p( 1 :: n ) to a sieve of primes up to n %
    procedure Eratosthenes ( logical array p( * ) ; integer value n ) ;
    begin
        p( 1 ) := false; p( 2 ) := true;
        for i := 3 step 2 until n do p( i ) := true;
        for i := 4 step 2 until n do p( i ) := false;
        for i := 3 step 2 until truncate( sqrt( n ) ) do begin
            integer ii; ii := i + i;
            if p( i ) then for pr := i * i step ii until n do p( pr ) := false
        end for_i ;
    end Eratosthenes ;
    % find circular primes in p in the range lo to hi, if they are circular, flag the %
    % permutations as non-prime so we do not consider them again                      %
    % non-circular primes are also flageed as non-prime                               %
    % lo must be a power of ten and hi must be at most ( lo * 10 ) - 1                %
    procedure keepCircular ( logical array p ( * ); integer value lo, hi ) ;
        for n := lo until hi do begin
            if p( n ) then begin
                % have a prime %
                integer       c, pCount;
                logical       isCircular;
                integer array permutations ( 1 :: 10 );
                c          := n;
                isCircular := true;
                pCount     := 0;
                % cyclically permute c until we get back to p or find a non-prime value for c %
                while begin
                    integer first, rest;
                    first      := c div lo;
                    rest       := c rem lo;
                    c          := ( rest * 10 ) + first;
                    isCircular := p( c );
                    c not = n and isCircular
                end do begin
                    pCount := pCount + 1;
                    permutations( pCount ) := c
                end while_have_another_prime_permutation ;
                if not isCircular
                then p( n ) := false
                else begin
                    % have a circular prime - flag the permutations as non-prime %
                    for i := 1 until pCount do p( permutations( i ) ) := false
                end if_not_isCircular__
            end if_p_n
        end keepCircular ;
    integer       cCount;
    % sieve the primes up to 999999 %
    logical array p ( 1 ::   999999 );
    Eratosthenes( p,         999999 );
    % remove non-circular primes from the sieve %
    % the single digit primes are all circular so we start at 10 %
    keepCircular( p,     10,     99 );
    keepCircular( p,    100,    999 );
    keepCircular( p,   1000,   9999 );
    keepCircular( p,  10000,  99999 );
    keepCircular( p, 100000, 200000 );
    % print the first 19 circular primes %
    cCount := 0;
    write( "First 19 circular primes: " );
    for i := 1 until 200000 do begin
        if p( i ) then begin
            writeon( i_w := 1, s_w := 1, i );
            cCount := cCount + 1;
            if cCount = 19 then goto end_circular
        end if_p_i
    end for_i ;
end_circular:
end.


perms: function [n][
    str: repeat to :string n 2
    result: new []
    lim: dec size digits n
    loop 0..lim 'd ->
        'result ++ slice str d lim+d

    return to [:integer] result
]

circulars: new []

circular?: function [x][
    if not? prime? x -> return false

    loop perms x 'y [
        if not? prime? y -> return false
        if contains? circulars y -> return false
    ]

    'circulars ++ x

    return true
]

i: 2
found: 0
while [found < 19][
    if circular? i [
        print i
        found: found + 1
    ]
    i: i + 1
]


class Shape a where
    perimeter :: a -> Double
    area      :: a -> Double
{- A type class Shape. Types belonging to Shape must support two
methods, perimeter and area. -}

data Rectangle = Rectangle Double Double
{- A new type with a single constructor. In the case of data types
which have only one constructor, we conventionally give the
constructor the same name as the type, though this isn't mandatory. -}

data Circle = Circle Double

instance Shape Rectangle where
    perimeter (Rectangle width height) = 2 * width + 2 * height
    area      (Rectangle width height) = width * height
{- We made Rectangle an instance of the Shape class by
implementing perimeter, area :: Rectangle -> Int. -}

instance Shape Circle where
    perimeter (Circle radius) = 2 * pi * radius
    area      (Circle radius) = pi * radius^2

apRatio :: Shape a => a -> Double
{- A simple polymorphic function. -}
apRatio shape = area shape / perimeter shape

main = do
    print $ apRatio $ Circle 5
    print $ apRatio $ Rectangle 5 5
{- The correct version of apRatio (and hence the correct
implementations of perimeter and area) is chosen based on the type
of the argument. -}


class Example (x) # 'x' is a field in class

  # method definition
  method double ()
    return 2 * x
  end

  # 'initially' block is called on instance construction
  initially (x)
    if /x # if x is null (not given), then set field to 0
      then self.x := 0
      else self.x := x
end

procedure main ()
  x1 := Example ()  # new instance with default value of x
  x2 := Example (2) # new instance with given value of x
  write (x1.x)
  write (x2.x)
  write (x2.double ()) # call a method
end


# syntax: GAWK -f CIRCULAR_PRIMES.AWK
BEGIN {
    p = 2
    printf("first 19 circular primes:")
    for (count=0; count<19; p++) {
      if (is_circular_prime(p)) {
        printf(" %d",p)
        count++
      }
    }
    printf("\n")
    exit(0)
}
function cycle(n,  m,p) { # E.G. if n = 1234 returns 2341
    m = n
    p = 1
    while (m >= 10) {
      p *= 10
      m /= 10
    }
    return int(m+10*(n%p))
}
function is_circular_prime(p,  p2) {
    if (!is_prime(p)) {
      return(0)
    }
    p2 = cycle(p)
    while (p2 != p) {
      if (p2 < p || !is_prime(p2)) {
        return(0)
      }
      p2 = cycle(p2)
    }
    return(1)
}
function is_prime(x,  i) {
    if (x <= 1) {
      return(0)
    }
    for (i=2; i<=int(sqrt(x)); i++) {
      if (x % i == 0) {
        return(0)
      }
    }
    return(1)
}


#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>

bool is_prime(uint32_t n) {
    if (n == 2)
        return true;
    if (n < 2 || n % 2 == 0)
        return false;
    for (uint32_t p = 3; p * p <= n; p += 2) {
        if (n % p == 0)
            return false;
    }
    return true;
}

// e.g. returns 2341 if n = 1234
uint32_t cycle(uint32_t n) {
    uint32_t m = n, p = 1;
    while (m >= 10) {
        p *= 10;
        m /= 10;
    }
    return m + 10 * (n % p);
}

bool is_circular_prime(uint32_t p) {
    if (!is_prime(p))
        return false;
    uint32_t p2 = cycle(p);
    while (p2 != p) {
        if (p2 < p || !is_prime(p2))
            return false;
        p2 = cycle(p2);
    }
    return true;
}

void test_repunit(uint32_t digits) {
    char* str = malloc(digits + 1);
    if (str == 0) {
        fprintf(stderr, "Out of memory\n");
        exit(1);
    }
    memset(str, '1', digits);
    str[digits] = 0;
    mpz_t bignum;
    mpz_init_set_str(bignum, str, 10);
    free(str);
    if (mpz_probab_prime_p(bignum, 10))
        printf("R(%u) is probably prime.\n", digits);
    else
        printf("R(%u) is not prime.\n", digits);
    mpz_clear(bignum);
}

int main() {
    uint32_t p = 2;
    printf("First 19 circular primes:\n");
    for (int count = 0; count < 19; ++p) {
        if (is_circular_prime(p)) {
            if (count > 0)
                printf(", ");
            printf("%u", p);
            ++count;
        }
    }
    printf("\n");
    printf("Next 4 circular primes:\n");
    uint32_t repunit = 1, digits = 1;
    for (; repunit < p; ++digits)
        repunit = 10 * repunit + 1;
    mpz_t bignum;
    mpz_init_set_ui(bignum, repunit);
    for (int count = 0; count < 4; ) {
        if (mpz_probab_prime_p(bignum, 15)) {
            if (count > 0)
                printf(", ");
            printf("R(%u)", digits);
            ++count;
        }
        ++digits;
        mpz_mul_ui(bignum, bignum, 10);
        mpz_add_ui(bignum, bignum, 1);
    }
    mpz_clear(bignum);
    printf("\n");
    test_repunit(5003);
    test_repunit(9887);
    test_repunit(15073);
    test_repunit(25031);
    test_repunit(35317);
    test_repunit(49081);
    return 0;
}


coclass 'exampleClass'

exampleMethod=: monad define
 1+exampleInstanceVariable
)

create=: monad define
 'this is the constructor'
)

exampleInstanceVariable=: 0


public class MyClass{

  // instance variable
  private int variable;  // Note: instance variables are usually "private"

  /**
  * The constructor
  */
  public MyClass(){
    // creates a new instance
  }

  /**
  * A method
  */
  public void someMethod(){
   this.variable = 1;
  }
}


#include <cstdint>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <gmpxx.h>

typedef mpz_class integer;

bool is_prime(const integer& n, int reps = 50) {
    return mpz_probab_prime_p(n.get_mpz_t(), reps);
}

std::string to_string(const integer& n) {
    std::ostringstream out;
    out << n;
    return out.str();
}

bool is_circular_prime(const integer& p) {
    if (!is_prime(p))
        return false;
    std::string str(to_string(p));
    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {
        std::rotate(str.begin(), str.begin() + 1, str.end());
        integer p2(str, 10);
        if (p2 < p || !is_prime(p2))
            return false;
    }
    return true;
}

integer next_repunit(const integer& n) {
    integer p = 1;
    while (p < n)
        p = 10 * p + 1;
    return p;
}

integer repunit(int digits) {
    std::string str(digits, '1');
    integer p(str);
    return p;
}

void test_repunit(int digits) {
    if (is_prime(repunit(digits), 10))
        std::cout << "R(" << digits << ") is probably prime\n";
    else
        std::cout << "R(" << digits << ") is not prime\n";
}

int main() {
    integer p = 2;
    std::cout << "First 19 circular primes:\n";
    for (int count = 0; count < 19; ++p) {
        if (is_circular_prime(p)) {
            if (count > 0)
                std::cout << ", ";
            std::cout << p;
            ++count;
        }
    }
    std::cout << '\n';
    std::cout << "Next 4 circular primes:\n";
    p = next_repunit(p);
    std::string str(to_string(p));
    int digits = str.size();
    for (int count = 0; count < 4; ) {
        if (is_prime(p, 15)) {
            if (count > 0)
                std::cout << ", ";
            std::cout << "R(" << digits << ")";
            ++count;
        }
        p = repunit(++digits);
    }
    std::cout << '\n';
    test_repunit(5003);
    test_repunit(9887);
    test_repunit(15073);
    test_repunit(25031);
    test_repunit(35317);
    test_repunit(49081);
    return 0;
}


//Constructor function.
function Car(brand, weight) {
  this.brand = brand;
  this.weight = weight || 1000; // Resort to default value (with 'or' notation).
}
Car.prototype.getPrice = function() { // Method of Car.
  return this.price;
}

function Truck(brand, size) {
  this.car = Car;
  this.car(brand, 2000); // Call another function, modifying the "this" object (e.g. "superconstructor".)
  this.size = size; // Custom property for just this object.
}
Truck.prototype = Car.prototype; // Also "import" the prototype from Car.

var cars = [ // Some example car objects.
  new Car("Mazda"),
  new Truck("Volvo", 2)
];
for (var i=0; i<cars.length; i++) {
  alert(cars[i].brand + " " + cars[i].weight + " " + cars[i].size + ", " +
      (cars[i] instanceof Car) + " " + (cars[i] instanceof Truck));
}


abstract type Mammal end
habitat(::Mammal) = "planet Earth"

struct Whale <: Mammal
    mass::Float64
    habitat::String
end
Base.show(io::IO, ::Whale) = print(io, "a whale")
habitat(w::Whale) = w.habitat

struct Wolf <: Mammal
    mass::Float64
end
Base.show(io::IO, ::Wolf) = print(io, "a wolf")

arr = [Whale(1000, "ocean"), Wolf(50)]
println("Type of $arr is ", typeof(arr))
for a in arr
    println("Habitat of $a: ", habitat(a))
end


BYTE FUNC AtasciiToInternal(CHAR c)
  BYTE c2

  c2=c&$7F
  IF c2<32 THEN RETURN (c+64)
  ELSEIF c2<96 THEN RETURN (c-32) FI
RETURN (c)

PROC CharOut(CARD x BYTE y CHAR c)
  BYTE i,j,v
  CARD addr

  addr=$E000+AtasciiToInternal(c)*8
  FOR j=0 TO 7
  DO
    v=Peek(addr) i=8
    WHILE i>0
    DO
      IF (v&1)=0 THEN Color=0
      ELSE Color=1 FI
      Plot(x+i,y+j)
      v=v RSH 1 i==-1
    OD
    addr==+1
  OD
RETURN

PROC TextOut(CARD x BYTE y CHAR ARRAY text)
  BYTE i

  FOR i=1 TO text(0)
  DO
    CharOut(x,y,text(i))
    x==+8
  OD
RETURN

PROC DrawDigit(BYTE d INT x BYTE y INT dx,dy)
  IF d=1 THEN
    Plot(x,y) DrawTo(x+dx,y)
  ELSEIF d=2 THEN
    Plot(x,y+dy) DrawTo(x+dx,y+dy)
  ELSEIF d=3 THEN
    Plot(x,y) DrawTo(x+dx,y+dy)
  ELSEIF d=4 THEN
    Plot(x,y+dy) DrawTo(x+dx,y)
  ELSEIF d=5 THEN
    Plot(x,y) DrawTo(x+dx,y) DrawTo(x,y+dy)
  ELSEIF d=6 THEN
    Plot(x+dx,y) DrawTo(x+dx,y+dy)
  ELSEIF d=7 THEN
    Plot(x,y) DrawTo(x+dx,y) DrawTo(x+dx,y+dy)
  ELSEIF d=8 THEN
    Plot(x,y+dy) DrawTo(x+dx,y+dy) DrawTo(x+dx,y)
  ELSEIF d=9 THEN
    Plot(x,y) DrawTo(x+dx,y)
    DrawTo(x+dx,y+dy) DrawTo(x,y+dy)
  FI
RETURN

PROC Cystersian(CARD n INT x BYTE y,s)
  INT ms

  ms=-s
  Color=1
  Plot(x+s,y) DrawTo(x+s,y+3*s)

  DrawDigit(n MOD 10,x+s,y,s,s)
  n==/10
  DrawDigit(n MOD 10,x+s,y,ms,s)
  n==/10
  DrawDigit(n MOD 10,x+s,y+3*s,s,ms)
  n==/10
  DrawDigit(n MOD 10,x+s,y+3*s,ms,ms)
RETURN

PROC Test(CARD n INT x BYTE y,s)
  CHAR ARRAY text(5)

  StrC(n,text)
  TextOut(x+(2*s-text(0)*8)/2,y-10,text)
  Cystersian(n,x,y,s)
RETURN

PROC Main()
  CARD ARRAY numbers=[0 1 20 300 4000 5555 6789 6502 1977 2021]
  BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
  BYTE s=[16],i
  INT x,y

  Graphics(8+16)
  COLOR1=$0C
  COLOR2=$02

  x=s y=2*s
  FOR i=0 TO 9
  DO
    Test(numbers(i),x,y,s)
    x==+4*s
    IF x>=320-s THEN
      x=s y==+5*s
    FI
  OD

  DO UNTIL CH#$FF OD
  CH=$FF
RETURN


class MyClass(val myInt: Int) {
   fun treble(): Int = myInt * 3
}

fun main(args: Array<String>) {
    val mc = MyClass(24)
    print("${mc.myInt}, ${mc.treble()}")
}


define mytype => type {
	data
		public id::integer		= 0,
		public val::string		= '',
		public rand::integer	= 0

	public onCreate() => {
		// "onCreate" runs when instance created, populates .rand
		.rand = math_random(50,1)
	}
	public asString() => {
		return 'has a value of: "'+.val+'" and a rand number of "'+.rand+'"'
	}

}

local(x = mytype)
#x->val = '99 Bottles of beer'
#x->asString // outputs 'has a value of: "99 Bottles of beer" and a rand number of "48"'


(defmodule simple-object
  (export all))

(defun fish-class (species)
  "
  This is the constructor used internally, once the children and fish id are
  known.
  "
  (let ((habitat '"water"))
    (lambda (method-name)
      (case method-name
        ('habitat
          (lambda (self) habitat))
        ('species
          (lambda (self) species))))))

(defun get-method (object method-name)
  "
  This is a generic function, used to call into the given object (class
  instance).
  "
  (funcall object method-name))

; define object methods
(defun get-habitat (object)
  "Get a variable set in the class."
  (funcall (get-method object 'habitat) object))

(defun get-species (object)
  "Get a variable passed when constructing the object."
  (funcall (get-method object 'species) object))


// Circular primes - Nigel Galloway: September 13th., 2021
let fG n g=let rec fG y=if y=g then true else if y>g && isPrime y then fG(10*(y%n)+y/n) else false in fG(10*(g%n)+g/n)
let rec fN g l=seq{let g=[for n in g do for g in [1;3;7;9] do let g=n*10+g in yield g] in yield! g|>List.filter(fun n->isPrime n && fG l n); yield! fN g (l*10)}
let circP()=seq{yield! [2;3;5;7]; yield! fN [1;3;7;9] 10}
circP()|> Seq.take 19 |>Seq.iter(printf "%d "); printfn ""
printf "The first 5 repunit primes are "; rUnitP(10)|>Seq.take 5|>Seq.iter(fun n->printf $"R(%d{n}) "); printfn ""


USING: combinators.short-circuit formatting io kernel lists
lists.lazy math math.combinatorics math.functions math.parser
math.primes sequences sequences.extras ;

! Create an ordered infinite lazy list of circular prime
! "candidates" -- the numbers 2, 3, 5 followed by numbers
! composed of only the digits 1, 3, 7, and 9.

: candidates ( -- list )
    L{ "2" "3" "5" "7" } 2 lfrom
    [ "1379" swap selections >list ] lmap-lazy lconcat lappend ;

: circular-prime? ( str -- ? )
    all-rotations {
        [ [ infimum ] [ first = ] bi ]
        [ [ string>number prime? ] all? ]
    } 1&& ;

: circular-primes ( -- list )
    candidates [ circular-prime? ] lfilter ;

: prime-repunits ( -- list )
    7 lfrom [ 10^ 1 - 9 / prime? ] lfilter ;

"The first 19 circular primes are:" print
19 circular-primes ltake [ write bl ] leach nl nl

"The next 4 circular primes, in repunit format, are:" print
4 prime-repunits ltake [ "R(%d) " printf ] leach nl


# syntax: GAWK -f CISTERCIAN_NUMERALS.AWK [-v debug={0|1}] [-v xc=anychar] numbers 0-9999 ...
#
# example: GAWK -f CISTERCIAN_NUMERALS.AWK 0 1 20 300 4000 5555 6789 1995 10000
#
# sorting:
#   PROCINFO["sorted_in"] is used by GAWK
#   SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
    cistercian_init()
    for (i=1; i<=ARGC-1; i++) {
      cistercian1(ARGV[i])
    }
    exit(0)
}
function cistercian1(n,  i) {
    printf("\n%6s\n",n)
    if (!(n ~ /^[0-9]+$/ && length(n) <= 4)) {
      print("invalid")
      return
    }
    n = sprintf("%04d",n)
    cistercian2(2,1,substr(n,3,1),substr(n,4,1))
    for (i=1; i<=5; i++) { # separator between upper and lower parts
      printf("%5s%1s%5s\n","",xc,"")
    }
    cistercian2(4,3,substr(n,1,1),substr(n,2,1))
}
function cistercian2(i1,i2,n1,n2,  i,L,R) {
    for (i=1; i<=5; i++) {
      L = substr(cn_arr[i1][i],n1*6+2,5)
      R = substr(cn_arr[i2][i],n2*6+2,5)
      printf("%5s%1s%5s\n",L,xc,R)
    }
}
function cistercian_init(  header,i,j,LL,LR,UL,UR) {
# 1-9 upper-right
    cn_arr[1][++UR] = ":xxxxx:     :x    :    x:xxxxx:    x:xxxxx:    x:xxxxx:"
    cn_arr[1][++UR] = ":     :     : x   :   x :   x :    x:    x:    x:    x:"
    cn_arr[1][++UR] = ":     :     :  x  :  x  :  x  :    x:    x:    x:    x:"
    cn_arr[1][++UR] = ":     :     :   x : x   : x   :    x:    x:    x:    x:"
    cn_arr[1][++UR] = ":     :xxxxx:    x:x    :x    :    x:    x:xxxxx:xxxxx:"
# 10-90 upper-left
    cn_arr[2][++UL] = ":xxxxx:     :    x:x    :xxxxx:x    :xxxxx:x    :xxxxx:"
    cn_arr[2][++UL] = ":     :     :   x : x   : x   :x    :x    :x    :x    :"
    cn_arr[2][++UL] = ":     :     :  x  :  x  :  x  :x    :x    :x    :x    :"
    cn_arr[2][++UL] = ":     :     : x   :   x :   x :x    :x    :x    :x    :"
    cn_arr[2][++UL] = ":     :xxxxx:x    :    x:    x:x    :x    :xxxxx:xxxxx:"
# 100-900 lower-right
    cn_arr[3][++LR] = ":     :xxxxx:    x:x    :x    :    x:    x:xxxxx:xxxxx:"
    cn_arr[3][++LR] = ":     :     :   x : x   : x   :    x:    x:    x:    x:"
    cn_arr[3][++LR] = ":     :     :  x  :  x  :  x  :    x:    x:    x:    x:"
    cn_arr[3][++LR] = ":     :     : x   :   x :   x :    x:    x:    x:    x:"
    cn_arr[3][++LR] = ":xxxxx:     :x    :    x:xxxxx:    x:xxxxx:    x:xxxxx:"
# 1000-9000 lower-left
    cn_arr[4][++LL] = ":     :xxxxx:x    :    x:    x:x    :x    :xxxxx:xxxxx:"
    cn_arr[4][++LL] = ":     :     : x   :   x :   x :x    :x    :x    :x    :"
    cn_arr[4][++LL] = ":     :     :  x  :  x  :  x  :x    :x    :x    :x    :"
    cn_arr[4][++LL] = ":     :     :   x : x   : x   :x    :x    :x    :x    :"
    cn_arr[4][++LL] = ":xxxxx:     :    x:x    :xxxxx:x    :xxxxx:x    :xxxxx:"
    header =    ":00000:11111:22222:33333:44444:55555:66666:77777:88888:99999:"
    PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
    sub(/^ +/,"",xc)
    xc = (xc == "") ? "x" : substr(xc,1,1) # substitution character
    for (i in cn_arr) {
      for (j in cn_arr[i]) {
        gsub(/x/,xc,cn_arr[i][j]) # change "x" to substitution character
        cn_arr[i][j] = sprintf(":%5s%s","",cn_arr[i][j]) # add zero column to table
        if (debug == 1) { printf("%s %2s %d.%d\n",cn_arr[i][j],substr("URULLRLL",i*2-1,2),i,j) }
      }
    }
    if (debug == 1) { printf("%s\n",header) }
}


----------------------------------------
-- @desc      Class "MyClass"
-- @file      parent script "MyClass"
----------------------------------------

-- instance variable
property _myvar

-- constructor
on new (me)
  me._myvar = 23
  return me
end

-- a method
on doubleAndPrint (me)
  me._myvar = me._myvar * 2
  put me._myvar
end


Section Header

+ name := SAMPLE;

Section Inherit

- parent : OBJECT := OBJECT;

Section Private

+ variable : INTEGER <- 0;

Section Public

- some_method <- (
  variable := 1;
);

- main <- (
  + sample : SAMPLE;

  sample := SAMPLE.clone;
  sample.some_method;
);


:- object(metaclass,
    instantiates(metaclass)).

    :- public(new/2).
    new(Instance, Value) :-
        self(Class),
        create_object(Instance, [instantiates(Class)], [], [state(Value)]).

:- end_object.

:- object(class,
    instantiates(metaclass)).

    :- public(method/1).
    method(Value) :-
        ::state(Value).

    :- private(state/1).

:- end_object.


create 235-wheel 6 c, 4 c, 2 c, 4 c, 2 c, 4 c, 6 c, 2 c,
    does> swap 7 and + [email protected] ;

0 1 2constant init-235    \ roll 235 wheel at position 1
: next-235   over 235-wheel + swap 1+ swap ;

\ check that n is prime excepting multiples of 2, 3, 5.
: sq  dup * ;
: wheel-prime? ( n -- f )
    >r init-235 begin
        next-235
        dup sq [email protected] >    if  rdrop 2drop true  exit  then
        [email protected] over mod 0= if  rdrop 2drop false exit  then
    again ;

: prime? ( n -- f )
    dup 2 < if drop false exit then
    dup 2 mod 0= if 2 = exit then
    dup 3 mod 0= if 3 = exit then
    dup 5 mod 0= if 5 = exit then
    wheel-prime? ;

: log10^ ( n -- 10^[log n], log n )
    dup 0<= abort" log10^: argument error."
    1 0 rot
    begin dup 9 > while
        >r  swap 10 *  swap 1+  r> 10 /
    repeat drop ;

: log10  ( n -- n )  log10^ nip ;

: rotate ( n -- n )
    dup log10^ drop /mod swap 10 * + ;

: prime-rotation? ( p0 p -- f )
    tuck <= swap prime? and ;

: circular? ( n -- f )  \ assume n is not a multiple of 2, 3, 5
    dup wheel-prime? invert
    if  drop false exit
    then dup >r true
    over log10 0 ?do
        swap rotate j over prime-rotation? rot and
    loop nip rdrop ;

: .primes
    2 . 3 . 5 .
    16 init-235  \ -- count, [n1 n2] as 2,3,5 wheel
    begin
        next-235 dup circular?
        if dup . rot 1- -rot
        then
    third 0= until 2drop drop ;

." The first 19 circular primes are:" cr .primes cr
bye


#define floor(x) ((x*2.0-0.5)Shr 1)

Function isPrime(Byval p As Integer) As Boolean
    If p < 2 Then Return False
    If p Mod 2 = 0 Then Return p = 2
    If p Mod 3 = 0 Then Return p = 3
    Dim As Integer d = 5
    While d * d <= p
        If p Mod d = 0 Then Return False Else d += 2
        If p Mod d = 0 Then Return False Else d += 4
    Wend
    Return True
End Function

Function isCircularPrime(Byval p As Integer) As Boolean
    Dim As Integer n = floor(Log(p)/Log(10))
    Dim As Integer m = 10^n, q = p
    For i As Integer = 0 To n
        If (q < p Or Not isPrime(q)) Then Return false
        q = (q Mod m) * 10 + floor(q / m)
    Next i
    Return true
End Function

Dim As Integer p = 2, dp = 1, cont = 0
Print("Primeros 19 primos circulares:")
While cont < 19
    If isCircularPrime(p) Then Print p;" "; : cont += 1
    p += dp: dp = 2
Wend
Sleep


#include <stdio.h>

#define GRID_SIZE 15
char canvas[GRID_SIZE][GRID_SIZE];

void initN() {
    int i, j;
    for (i = 0; i < GRID_SIZE; i++) {
        for (j = 0; j < GRID_SIZE; j++) {
            canvas[i][j] = ' ';
        }
        canvas[i][5] = 'x';
    }
}

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

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

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

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

void drawOnes(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:
        drawOnes(1);
        drawOnes(4);
        break;
    case 6:
        vertical(0, 4, 10);
        break;
    case 7:
        drawOnes(1);
        drawOnes(6);
        break;
    case 8:
        drawOnes(2);
        drawOnes(6);
        break;
    case 9:
        drawOnes(1);
        drawOnes(8);
        break;
    default:
        break;
    }
}

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

void drawHundreds(int hundreds) {
    switch (hundreds) {
    case 1:
        horizontal(6, 10, 14);
        break;
    case 2:
        horizontal(6, 10, 10);
        break;
    case 3:
        diagu(6, 10, 14);
        break;
    case 4:
        diagd(6, 10, 10);
        break;
    case 5:
        drawHundreds(1);
        drawHundreds(4);
        break;
    case 6:
        vertical(10, 14, 10);
        break;
    case 7:
        drawHundreds(1);
        drawHundreds(6);
        break;
    case 8:
        drawHundreds(2);
        drawHundreds(6);
        break;
    case 9:
        drawHundreds(1);
        drawHundreds(8);
        break;
    default:
        break;
    }
}

void drawThousands(int thousands) {
    switch (thousands) {
    case 1:
        horizontal(0, 4, 14);
        break;
    case 2:
        horizontal(0, 4, 10);
        break;
    case 3:
        diagd(0, 4, 10);
        break;
    case 4:
        diagu(0, 4, 14);
        break;
    case 5:
        drawThousands(1);
        drawThousands(4);
        break;
    case 6:
        vertical(10, 14, 0);
        break;
    case 7:
        drawThousands(1);
        drawThousands(6);
        break;
    case 8:
        drawThousands(2);
        drawThousands(6);
        break;
    case 9:
        drawThousands(1);
        drawThousands(8);
        break;
    default:
        break;
    }
}

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

    int hundreds = v / 100;
    v %= 100;

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

    if (thousands > 0) {
        drawThousands(thousands);
    }
    if (hundreds > 0) {
        drawHundreds(hundreds);
    }
    if (tens > 0) {
        drawTens(tens);
    }
    if (ones > 0) {
        drawOnes(ones);
    }
}

void write(FILE *out) {
    int i;
    for (i = 0; i < GRID_SIZE; i++) {
        fprintf(out, "%-.*s", GRID_SIZE, canvas[i]);
        putc('\n', out);
    }
}

void test(int n) {
    printf("%d:\n", n);
    initN();
    draw(n);
    write(stdout);
    printf("\n\n");
}

int main() {
    test(0);
    test(1);
    test(20);
    test(300);
    test(4000);
    test(5555);
    test(6789);
    test(9999);

    return 0;
}


myclass = setmetatable({
__index = function(z,i) return myclass[i] end, --this makes class variables a possibility
setvar = function(z, n) z.var = n end
}, {
__call = function(z,n) return setmetatable({var = n}, myclass) end
})

instance = myclass(3)

print(instance.var) -->3

instance:setvar(6)

print(instance.var) -->6


Class zz {
      module bb {
            Superclass A {
                  unique:
                  counter
            }
            Superclass B1 {
                  unique:
                  counter
            }
            Superclass B2 {
                  unique:
                  counter
            }
            \\ We can make a group Alfa with a member, another group Beta
            \\ Group Beta can't see parent group, but can see own member groups
            \\ Group Alfa can see everything in nested groups, in any level,
            \\ but can't see inside modules/functions/operator/value/set
            Group Alfa {
                  Group Beta { }
            }
            Alfa=A
            Alfa.Beta=B1
            \\ we make 3 groups for marshaling counters
            \\ each group get a superclass
            Marshal1=A
            Marshal2=B1
            Marshal3=B2
            \\ Now we want to add functionality7
            \\ Inc module to add 1 to counter
            \\ a Value function to return counter
            \\ Without Value a group return a copy
            \\ If a group has a value then we can get copy using Group(nameofgroup)
            \\ just delete Group Marshal1 and remove Rem when we make Marshal1 using a class function
            Group Marshal1 {
                  Module Inc {
                        For SuperClass {.counter++}
                  }
                  Value {
                        For SuperClass {=.counter}
                  }
            }
            Class AnyMarshal {
                  Module Inc {
                        For SuperClass {.counter++}
                  }
                  Value {
                        For SuperClass {=.counter}
                  }
            }
            \\ here we merge groups
            Rem : Marshal1=AnyMarshal()
            Marshal2=AnyMarshal()
            Marshal3=AnyMarshal()

            \\ So now we see counters (three zero)
            Print Marshal1, Marshal2, Marshal3 \\ 0, 0, 0
            \\ Now we prepare Alfa and Alfa.Beta groups
            Group Alfa {
                  Group Beta {
                        Function SuperClass.Counter {
                              For SuperClass {
                                    =.counter
                              }
                        }
                  }
                  Module PrintData {
                        For SuperClass {
                              Print .counter, This.Beta.SuperClass.Counter()
                        }
                  }
            }
            \\ some marshaling to counters
            Marshal1.inc
            Marshal2.inc
            Marshal2.inc
            Marshal3.inc
            \\ lets print results
            Print Marshal1, Marshal2, Marshal3 \\ 1   2   1
            \\ Calling Alfa.PrintData
            Alfa.PrintData  \\ 1   2
            \\ Merging a group in a group make a change to superclass pointer inside group
            Alfa.Beta=B2 \\ change supeclass
            Alfa.PrintData  \\ 1   1
            For i=1 to 10 : Marshal3.inc : Next i
            Alfa.PrintData  \\ 1   11
            Alfa.Beta=B1 \\ change supeclass
            Alfa.PrintData  \\ 1   2
            Epsilon=Alfa
            Print Valid(@alfa as epsilon), Valid(@alfa.beta as epsilon.beta) \\ -1   -1
            Epsilon.PrintData \\ 1 2
            Alfa.Beta=B2 \\ change supeclass
            Alfa.PrintData  \\ 1   11
            Epsilon.PrintData \\ 1 2
            \\ validation being for top group superclass and all members if are same
            \\ but not for inner superclasses. This maybe change in later revisions of language.
            Print Valid(@alfa as epsilon), Valid(@alfa.beta as epsilon.beta) \\ -1  0

      }
}
Dim A(10)
A(3)=zz()
A(3).bb

Report {
	there is no super like java super in M2000 when we use inheritance through classes
	see Superclass (example SUP) which is something differnent
	}

class Shape {
private:
    super.X, super.Y
    Function super.toString$(a=10) {
        ="Shape(" + str$(.super.X,"") + ", " + str$(.super.Y,"") + ")"
    }
public:
       Module final setPosition (px, py) {
           .super.X <= px
           .super.Y <= py
       }
        Function toString$() {
        =.super.toString$()
    }
}
class MoveShape {
      Module MoveRelative(xr, yr) {
            .super.X+=xr
            .super.Y+=yr
      }
}
class Circle as MoveShape as Shape {
private:
    radius
public:
    Module setRadius (r) {
        .radius <= r
    }
    Function toString$() {
        = .super.toString$() + ": Circle(" + str$(.radius,"") + ")"
    }
}

class Rectangle as MoveShape  as Shape {
private:
    height, width
public:
      Module MoveLeftSide (p as *Rectangle) {
      \\ for same type objects private members are like public
           for This, p {
               .super.X<=..super.X+..width
               .super.Y<=..super.Y
           }
      }
    module setDimensions (h,w) {
        .height <= h
        .width <= w
    }
    Function toString$() {
       = .super.toString$() + ": Rectangle(" + str$(.height,"") + " x " + str$(.width,"") + ")"
    }
}
c =Circle()
r = Rectangle()

r.setPosition 1, 2
r.setDimensions 50, 50
c.setPosition 3, 4
c.setRadius 10
Print r.tostring$()
Print c.tostring$()
r.MoveRelative 100,100
c.MoveRelative -50,-50
Print r.tostring$()
Print c.tostring$()

Report  {
	wokring with pointers like in c++
	pointers in M2000 are objects, so null pointer (pc->0&) isn't a zero, but an empty Group (object)
	}
pc->circle()
pr->rectangle()
pr=>setPosition 1, 2
pr=>setDimensions 50, 50
pc=>setPosition 3, 4
pc=>setRadius 10
Print pr=>tostring$()
Print pc=>tostring$()
\\ we can open up to ten objects (from one to ten dots, normaly one to three)
\\ if we use nestef for object {} also we have up to ten objects in total
\\ every for object {} is an area for temporary definitions, after exit from brackets
\\ any new definition erased.
For pr, pc {
	.MoveRelative 100,100
	..MoveRelative -50,-50
	Print .tostring$()
	Print ..tostring$()
}
pr2->rectangle()
pr2=>SetDimensions 30, 30
pr2=>MoveLeftSide pr
Print pr2=>toString$()


package main

import (
    "fmt"
    big "github.com/ncw/gmp"
    "strings"
)

// OK for 'small' numbers.
func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        d := 5
        for d*d <= n {
            if n%d == 0 {
                return false
            }
            d += 2
            if n%d == 0 {
                return false
            }
            d += 4
        }
        return true
    }
}

func repunit(n int) *big.Int {
    ones := strings.Repeat("1", n)
    b, _ := new(big.Int).SetString(ones, 10)
    return b
}

var circs = []int{}

// binary search is overkill for a small number of elements
func alreadyFound(n int) bool {
    for _, i := range circs {
        if i == n {
            return true
        }
    }
    return false
}

func isCircular(n int) bool {
    nn := n
    pow := 1 // will eventually contain 10 ^ d where d is number of digits in n
    for nn > 0 {
        pow *= 10
        nn /= 10
    }
    nn = n
    for {
        nn *= 10
        f := nn / pow // first digit
        nn += f * (1 - pow)
        if alreadyFound(nn) {
            return false
        }
        if nn == n {
            break
        }
        if !isPrime(nn) {
            return false
        }
    }
    return true
}

func main() {
    fmt.Println("The first 19 circular primes are:")
    digits := [4]int{1, 3, 7, 9}
    q := []int{1, 2, 3, 5, 7, 9}  // queue the numbers to be examined
    fq := []int{1, 2, 3, 5, 7, 9} // also queue the corresponding first digits
    count := 0
    for {
        f := q[0]   // peek first element
        fd := fq[0] // peek first digit
        if isPrime(f) && isCircular(f) {
            circs = append(circs, f)
            count++
            if count == 19 {
                break
            }
        }
        copy(q, q[1:])   // pop first element
        q = q[:len(q)-1] // reduce length by 1
        copy(fq, fq[1:]) // ditto for first digit queue
        fq = fq[:len(fq)-1]
        if f == 2 || f == 5 { // if digits > 1 can't contain a 2 or 5
            continue
        }
        // add numbers with one more digit to queue
        // only numbers whose last digit >= first digit need be added
        for _, d := range digits {
            if d >= fd {
                q = append(q, f*10+d)
                fq = append(fq, fd)
            }
        }
    }
    fmt.Println(circs)
    fmt.Println("\nThe next 4 circular primes, in repunit format, are:")
    count = 0
    var rus []string
    for i := 7; count < 4; i++ {
        if repunit(i).ProbablyPrime(10) {
            count++
            rus = append(rus, fmt.Sprintf("R(%d)", i))
        }
    }
    fmt.Println(rus)
    fmt.Println("\nThe following repunits are probably circular primes:")
    for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} {
        fmt.Printf("R(%-5d) : %t\n", i, repunit(i).ProbablyPrime(10))
    }
}


#include <array>
#include <iostream>

template<typename T, size_t S>
using FixedSquareGrid = std::array<std::array<T, S>, S>;

struct Cistercian {
public:
    Cistercian() {
        initN();
    }

    Cistercian(int v) {
        initN();
        draw(v);
    }

    Cistercian &operator=(int v) {
        initN();
        draw(v);
    }

    friend std::ostream &operator<<(std::ostream &, const Cistercian &);

private:
    FixedSquareGrid<char, 15> canvas;

    void initN() {
        for (auto &row : canvas) {
            row.fill(' ');
            row[5] = 'x';
        }
    }

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

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

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

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

    void drawOnes(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:
            drawOnes(1);
            drawOnes(4);
            break;
        case 6:
            vertical(0, 4, 10);
            break;
        case 7:
            drawOnes(1);
            drawOnes(6);
            break;
        case 8:
            drawOnes(2);
            drawOnes(6);
            break;
        case 9:
            drawOnes(1);
            drawOnes(8);
            break;
        default:
            break;
        }
    }

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

    void drawHundreds(int hundreds) {
        switch (hundreds) {
        case 1:
            horizontal(6, 10, 14);
            break;
        case 2:
            horizontal(6, 10, 10);
            break;
        case 3:
            diagu(6, 10, 14);
            break;
        case 4:
            diagd(6, 10, 10);
            break;
        case 5:
            drawHundreds(1);
            drawHundreds(4);
            break;
        case 6:
            vertical(10, 14, 10);
            break;
        case 7:
            drawHundreds(1);
            drawHundreds(6);
            break;
        case 8:
            drawHundreds(2);
            drawHundreds(6);
            break;
        case 9:
            drawHundreds(1);
            drawHundreds(8);
            break;
        default:
            break;
        }
    }

    void drawThousands(int thousands) {
        switch (thousands) {
        case 1:
            horizontal(0, 4, 14);
            break;
        case 2:
            horizontal(0, 4, 10);
            break;
        case 3:
            diagd(0, 4, 10);
            break;
        case 4:
            diagu(0, 4, 14);
            break;
        case 5:
            drawThousands(1);
            drawThousands(4);
            break;
        case 6:
            vertical(10, 14, 0);
            break;
        case 7:
            drawThousands(1);
            drawThousands(6);
            break;
        case 8:
            drawThousands(2);
            drawThousands(6);
            break;
        case 9:
            drawThousands(1);
            drawThousands(8);
            break;
        default:
            break;
        }
    }

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

        int hundreds = v / 100;
        v %= 100;

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

        if (thousands > 0) {
            drawThousands(thousands);
        }
        if (hundreds > 0) {
            drawHundreds(hundreds);
        }
        if (tens > 0) {
            drawTens(tens);
        }
        if (ones > 0) {
            drawOnes(ones);
        }
    }
};

std::ostream &operator<<(std::ostream &os, const Cistercian &c) {
    for (auto &row : c.canvas) {
        for (auto cell : row) {
            os << cell;
        }
        os << '\n';
    }
    return os;
}

int main() {
    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {
        std::cout << number << ":\n";

        Cistercian c(number);
        std::cout << c << '\n';
    }

    return 0;
}


function GenericClassInstance = GenericClass(varargin)

        if isempty(varargin) %No input arguments
            GenericClassInstance.classVariable = 0; %Generates a struct
        else
            GenericClassInstance.classVariable = varargin{1}; %Generates a struct
        end

        %Converts the struct to a class of type GenericClass
        GenericClassInstance = class(GenericClassInstance,'GenericClass');

end


// MiniScript is prototype based
Weapon = { "name": "Sword", "damage": 3 }
Weapon.slice = function()
    print "Did " + self.damage + " damage with " + self.name
end function

wep = new Weapon  // Same as: wep = { "__isa": Weapon }

wep.name = "Lance"

wep.slice


% define a Rectangle "class"
var int: Rectangle(var int: width, var int: height) =
  let {
    var int: this;
    constraint Type(this) = Rectangle; %define the "type" of the instance
    %define some "instance methods"
    constraint area(this) = width*height;
    constraint width(this) = width;
    constraint height(this) = height;
  } in this;

%this enum should contain the list of class names
enum Type = {Rectangle};
function var Type: Type(var int:a);

%declare the "instance methods"
function var int: area(var int:this) = let {var int:result;} in result;
function var int: height(var int:a) = let {var int:result;} in result;
function var int: width(var int:a) = let {var int:result;} in result;

%create an instance of the "class"
var int: rect = Rectangle(3,4);
var int: area1 = area(rect);

solve satisfy;

% print the area of the rectangle
output [show(area1),"\n"];


import Math.NumberTheory.Primes (Prime, unPrime, nextPrime)
import Math.NumberTheory.Primes.Testing (isPrime, millerRabinV)
import Text.Printf (printf)

rotated :: [Integer] -> [Integer]
rotated xs
  | any (< head xs) xs = []
  | otherwise          = map asNum $ take (pred $ length xs) $ rotate xs
 where
  rotate [] = []
  rotate (d:ds) = ds <> [d] : rotate (ds <> [d])

asNum :: [Integer] -> Integer
asNum [] = 0
asNum n@(d:ds)
 | all (==1) n = read $ concatMap show n
 | otherwise = (d * (10 ^ length ds)) + asNum ds

digits :: Integer -> [Integer]
digits 0 = []
digits n = digits d <> [r]
 where (d, r) = n `quotRem` 10

isCircular :: Bool -> Integer -> Bool
isCircular repunit n
  | repunit = millerRabinV 0 n
  | n < 10 = True
  | even n = False
  | null rotations = False
  | any (<n) rotations = False
  | otherwise = all isPrime rotations
 where
  rotations = rotated $ digits n

repunits :: [Integer]
repunits = go 2
 where go n = asNum (replicate n 1) : go (succ n)

asRepunit :: Int -> Integer
asRepunit n = asNum $ replicate n 1

main :: IO ()
main = do
  printf "The first 19 circular primes are:\n%s\n\n" $ circular primes
  printf "The next 4 circular primes, in repunit format are:\n"
  mapM_ (printf "R(%d) ") $ reps repunits
  printf "\n\nThe following repunits are probably circular primes:\n"
  mapM_ (uncurry (printf "R(%d) : %s\n") . checkReps) [5003, 9887, 15073, 25031, 35317, 49081]
 where
  primes = map unPrime [nextPrime 1..]
  circular = show . take 19 . filter (isCircular False)
  reps = map (sum . digits). tail . take 5 . filter (isCircular True)
  checkReps = (,) <$> id <*> show . isCircular True . asRepunit


import std.stdio;

class Cistercian {
    private immutable SIZE = 15;
    private char[SIZE][SIZE] canvas;

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

    private void initN() {
        foreach (ref row; canvas) {
            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) {
        auto thousands = v / 1000;
        v %= 1000;

        auto hundreds = v / 100;
        v %= 100;

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

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

    private void drawPart(int v) {
        switch(v) {
            case 0:
                break;

            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;

            default:
                import std.conv;
                assert(false, "Not handled: " ~ v.to!string);
        }
    }

    public void toString(scope void delegate(const(char)[]) sink) const {
        foreach (row; canvas) {
            sink(row);
            sink("\n");
        }
    }
}

void main() {
    foreach (number; [0, 1, 20, 300, 4000, 5555, 6789, 9999]) {
        writeln(number, ':');
        auto c = new Cistercian(number);
        writeln(c);
    }
}


class MyClass
	declare name

	// constructors are methods with the same name as the class
	def MyClass(name)
		this.name = name
	end

	def getName()
		return name
	end
end

// instantiate a new MyClass object
inst = new(MyClass, "name string goes here")

// display the name value
println inst.getName()


public class MyClass
{
    public this() { }  // the constructor in Nemerle is always named 'this'

    public MyVariable : int
    {
        get;
        set;
    }

    public MyMethod() : void
    {
    }

}

def myInstance = MyClass();                                           // no 'new' keyword needed
myInstance.MyVariable = 42;                                           // set MyVariable
System.Console.WriteLine($"My variable is $(myInstance.MyVariable)")  // get MyVariable


class ClassExample

  properties private -- class scope
  foo = int

  properties public  -- publicly visible
  bar = boolean

  properties indirect -- generates bean patterns
  baz = String()

  method main(args=String[]) static -- main method
    clsex = ClassExample()   -- instantiate
    clsex.foo = 42
    clsex.baz = 'forty-two'
    clsex.bar = 0 -- boolean false
    clsex.test(clsex.foo)
    clsex.test(clsex.bar)
    clsex.test(clsex.baz)

  method test(s=int)
    aap = 1 -- local (stack) variable
    say s aap

  method test(s=String)
    noot = 2
    say s noot

  method test(s=boolean)
    mies = 3
    say s mies


R=: [: ". 'x' ,~ #&'1'
assert 11111111111111111111111111111111x -: R 32

Filter=: (#~`)(`:6)

rotations=: (|."0 1~ [email protected]#)&.(10&#.inv)
assert 123 231 312 -: rotations 123

primes_less_than=: i.&.:(p:inv)
assert 2 3 5 7 11 -: primes_less_than 12

NB. circular y --> y is the order of magnitude.
circular=: monad define
 P25=: ([: -. (0 e. 1 3 7 9 e.~ 10 #.inv ])&>)Filter primes_less_than 10^y  NB. Q25 are primes with 1 3 7 9 digits
 P=: 2 5 , P25
 en=: # P
 group=: en # 0
 next=: 1
 for_i. i. # group do.
  if. 0 = i { group do.       NB. if untested
   j =: P i. rotations i { P   NB. j are the indexes of the rotated numbers in the list of primes
   if. en e. j do.             NB. if any are unfound
    j=: j -. en                 NB. prepare to mark them all as searched, and failed.
    g=: _1
   else.
    g=: next                    NB. mark the set as found in a new group.  Because we can.
    next=: >: next
   end.
   group=: g j} group          NB. apply the tested mark
  end.
 end.
 group </. P
)