100 PROGRAM "PolySp.bas"
110 OPTION ANGLE DEGREES
120 LET CH=2
130 SET VIDEO X 40:SET VIDEO Y 27:SET VIDEO MODE 1:SET VIDEO COLOR 0
140 OPEN #1:"video:"
150 OPEN #2:"video:"
160 WHEN EXCEPTION USE POSERROR
170   FOR ANG=40 TO 150 STEP 2
180     IF CH=2 THEN
190       LET CH=1
200     ELSE
210       LET CH=2
220     END IF
230     CLEAR #CH
240     PLOT #CH:640,468,ANGLE 180;
250     FOR D=12 TO 740 STEP 4
260       PLOT #CH:FORWARD D,RIGHT ANG;
270     NEXT
280     DISPLAY #CH:AT 1 FROM 1 TO 27
290   NEXT
300 END WHEN
310 HANDLER POSERROR
320   LET D=740
330   CONTINUE
340 END HANDLER


require 'gl2 trig media/imagekit'
coinsert 'jgl2'

DT       =: %30       NB. seconds
ANGLE    =: 0.025p1   NB. radians
DIRECTION=: 0         NB. radians

POLY=: noun define
  pc poly;pn "Poly Spiral";
  minwh 320 320; cc isi isigraph;
)

poly_run=: verb define
  wd POLY,'pshow'
  wd 'timer ',":DT * 1000
)

poly_close=: verb define
  wd 'timer 0; pclose'
)

sys_timer_z_=: verb define
  recalcAngle_base_ ''
  wd 'psel poly; set isi invalid'
)

poly_isi_paint=: verb define
  drawPolyspiral DIRECTION
)

recalcAngle=: verb define
  DIRECTION=: 2p1 | DIRECTION + ANGLE
)

drawPolyspiral=: verb define
  glclear''
  x1y1 =. (glqwh'')%2
  a=. -DIRECTION
  len=. 5
  for_i. i.150 do.
    glpen glrgb Hue a % 2p1
    x2y2=. x1y1 + len*(cos,sin) a
    gllines <.x1y1,x2y2
    x1y1=. x2y2
    len=. len+3
    a=. 2p1 | a - DIRECTION
  end.
)

poly_run''


import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class PolySpiral extends JPanel {
    double inc = 0;

    public PolySpiral() {
        setPreferredSize(new Dimension(640, 640));
        setBackground(Color.white);

        new Timer(40, (ActionEvent e) -> {
            inc = (inc + 0.05) % 360;
            repaint();
        }).start();
    }

    void drawSpiral(Graphics2D g, int len, double angleIncrement) {

        double x1 = getWidth() / 2;
        double y1 = getHeight() / 2;
        double angle = angleIncrement;

        for (int i = 0; i < 150; i++) {

            g.setColor(Color.getHSBColor(i / 150f, 1.0f, 1.0f));

            double x2 = x1 + Math.cos(angle) * len;
            double y2 = y1 - Math.sin(angle) * len;
            g.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
            x1 = x2;
            y1 = y2;

            len += 3;

            angle = (angle + angleIncrement) % (Math.PI * 2);
        }
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        drawSpiral(g, 5, Math.toRadians(inc));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("PolySpiral");
            f.setResizable(true);
            f.add(new PolySpiral(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}


abstract type Jewel end

mutable struct RoseQuartz <: Jewel
    carats::Float64
    quality::String
end

mutable struct Sapphire <: Jewel
    color::String
    carats::Float64
    quality::String
end

color(j::RoseQuartz) = "rosepink"
color(j::Jewel) = "Use the loupe."
color(j::Sapphire) = j.color

function testtypecopy()
    a = Sapphire("blue", 5.0, "good")
    b = RoseQuartz(3.5, "excellent")

    j::Jewel = deepcopy(b)

    println("a is a Jewel? ", a isa Jewel)
    println("b is a Jewel? ", a isa Jewel)
    println("j is a Jewel? ", a isa Jewel)
    println("a is a Sapphire? ", a isa Sapphire)
    println("a is a RoseQuartz? ", a isa RoseQuartz)
    println("b is a Sapphire? ", b isa Sapphire)
    println("b is a RoseQuartz? ", b isa RoseQuartz)
    println("j is a Sapphire? ", j isa Sapphire)
    println("j is a RoseQuartz? ", j isa RoseQuartz)

    println("The color of j is ", color(j), ".")
    println("j is the same as b? ", j == b)
end

testtypecopy()


// version 1.1.2

open class Animal(val name: String, var age: Int) {
    open fun copy() = Animal(name, age)

    override fun toString() = "Name: $name, Age: $age"
}

class Dog(name: String, age: Int, val breed: String) : Animal(name, age) {
    override fun copy() = Dog(name, age, breed)

    override fun toString() = super.toString() + ", Breed: $breed"
}

fun main(args: Array<String>) {
    val a: Animal = Dog("Rover", 3, "Terrier")
    val b: Animal = a.copy()  // calls Dog.copy() because runtime type of 'a' is Dog
    println("Dog 'a' = $a")   // implicitly calls Dog.toString()
    println("Dog 'b' = $b")   // ditto
    println("Dog 'a' is ${if (a === b) "" else "not"} the same object as Dog 'b'")
}


T = { name=function(s) return "T" end, tostring=function(s) return "I am a "..s:name() end }

function clone(s) local t={} for k,v in pairs(s) do t[k]=v end return t end
S1 = clone(T)  S1.name=function(s) return "S1" end

function merge(s,t) for k,v in pairs(t) do s[k]=v end return s end
S2 = merge(clone(T), {name=function(s) return "S2" end})

function prototype(base,mixin) return merge(merge(clone(base),mixin),{prototype=base}) end
S3 = prototype(T, {name=function(s) return "S3" end})

print("T :  "..T:tostring())
print("S1:  " ..S1:tostring())
print("S2:  " ..S2:tostring())
print("S3:  " ..S3:tostring())
print("S3's parent:  "..S3.prototype:tostring())


<title>Polyspiral Generator</title>

  Color:
  <select id="color">
    <option value="red">red</option>
    <option value="darkred" selected>darkred</option>
    <option value="green">green</option>
    <option value="darkgreen">darkgreen</option>
    <option value="blue">blue</option>
    <option value="navy">navy</option>
    <option value="brown">brown</option>
    <option value="maroon">maroon</option>
    <option value="black">black</option>
  </select>
  Direction:
  <input id="dir" value="1" type="number" min="-1" max="1" size="1">
  Range:
  <input id="rng" value="10" type="number" min="10" max="4000" step="10" size="4">
  <input type="button" value="Plot it!" onclick="pspiral();">

    Polyspiral

  <canvas id="cvsId" width="640" height="640" style="border: 2px inset;"></canvas>


using Gtk, Graphics, Colors

const can = @GtkCanvas()
const win = GtkWindow(can, "Polyspiral", 360, 360)

const drawiters = 72
const colorseq = [colorant"blue", colorant"red", colorant"green", colorant"black", colorant"gold"]
const angleiters = [0, 0, 0]
const angles = [75, 100, 135, 160]

Base.length(v::Vec2) = sqrt(v.x * v.x + v.y * v.y)

function drawline(ctx, p1, p2, color, width=1)
    move_to(ctx, p1.x, p1.y)
    set_source(ctx, color)
    line_to(ctx, p2.x, p2.y)
    set_line_width(ctx, width)
    stroke(ctx)
end

@guarded draw(can) do widget
    δ(r, θ) = Vec2(r * cospi(θ/180), r * sinpi(θ/180))
    nextpoint(p, r, θ) = (dp = δ(r, θ); Point(p.x + dp.x, p.y + dp.y))
    colorindex = (angleiters[1] % 5) + 1
    colr = colorseq[colorindex]
    ctx = getgc(can)
    h = height(can)
    w = width(can)
    x = 0.5 * w
    y = 0.5 * h
    θ = angleiters[2] * rand() * 3
    δθ = angleiters[2]
    r = 5
    δr = 3
    p1 = Point(x, y)
    for i in 1:drawiters
        if angleiters[3] == 0
            set_source(ctx, colorant"gray90")
            rectangle(ctx, 0, 0, w, h)
            fill(ctx)
            continue
        end
        p2 = nextpoint(p1, r, θ)
        drawline(ctx, p1, p2, colr, 2)
        θ = θ + δθ
        r = r + δr
        p1 = p2
    end
end

show(can)

while true
    angleiters[2] = angles[angleiters[1] % 3 + 1]
    angleiters[1] += 1
    angleiters[3] = angleiters[3] == 0 ? 1 : 0
    draw(can)
    yield()
    sleep(0.5)
end


// version 1.1.0

import java.awt.*
import java.awt.event.ActionEvent
import javax.swing.*

class PolySpiral() : JPanel() {
    private var inc = 0.0

    init {
        preferredSize = Dimension(640, 640)
        background = Color.white
        Timer(40) {
            inc = (inc + 0.05) % 360.0
            repaint()
        }.start()
    }

    private fun drawSpiral(g: Graphics2D, length: Int, angleIncrement: Double) {
        var x1 = width / 2.0
        var y1 = height / 2.0
        var len = length
        var angle = angleIncrement
        for (i in 0 until 150) {
            g.setColor(Color.getHSBColor(i / 150f, 1.0f, 1.0f))
            val x2 = x1 + Math.cos(angle) * len
            val y2 = y1 - Math.sin(angle) * len
            g.drawLine(x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt())
            x1 = x2
            y1 = y2
            len += 3
            angle = (angle + angleIncrement) % (Math.PI * 2.0)
        }
    }

    override protected fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        drawSpiral(g, 5, Math.toRadians(inc))
    }
}

fun main(args: Array<String>) {
    SwingUtilities.invokeLater {
        val f = JFrame()
        f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        f.title = "PolySpiral"
        f.setResizable(true)
        f.add(PolySpiral(), BorderLayout.CENTER)
        f.pack()
        f.setLocationRelativeTo(null)
        f.setVisible(true)
    }
}


LDA $19 ;load the value at memory address $19 into the accumulator
LDA #$19 ;load the value hexadecimal 19 (decimal 25) into the accumulator


T = {}
T.foo = function()
    return "This is an instance of T"
end function

S = new T
S.foo = function()
    return "This is an S for sure"
end function

instance = new S
print "instance.foo: " + instance.foo

copy = {}
copy = copy + instance  // copies all elements
print "copy.foo: " + copy.foo

// And to prove this is a copy, and not a reference:
instance.bar = 1
copy.bar = 2
print "instance.bar: " + instance.bar
print "copy.bar: " + copy.bar


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

-- -----------------------------------------------------------------------------
class RCPolymorphicCopy public

method copier(x = T) public static returns T
  return x.copy

method main(args = String[]) public constant
  obj1 = T()
  obj2 = S()
  System.out.println(copier(obj1).name) -- prints "T"
  System.out.println(copier(obj2).name) -- prints "S"
  return

-- -----------------------------------------------------------------------------
class RCPolymorphicCopy.T public implements Cloneable

method name returns String
  return T.class.getSimpleName

method copy public returns T
  dup = T

  do
    dup = T super.clone
  catch ex = CloneNotSupportedException
    ex.printStackTrace
  end

  return dup

-- -----------------------------------------------------------------------------
class RCPolymorphicCopy.S public extends RCPolymorphicCopy.T

method name returns String
  return S.class.getSimpleName


type
  T = ref object of RootObj
    myValue: string
  S1 = ref object of T
  S2 = ref object of T

method speak(x: T) {.base.} = echo "T Hello ", x.myValue
method speak(x: S1) = echo "S1 Meow ", x.myValue
method speak(x: S2) = echo "S2 Woof ", x.myValue

echo "creating initial objects of types S1, S2, and T."
var a = S1(myValue: "Green")
a.speak
var b = S2(myValue: "Blue")
b.speak
var u = T(myValue: "Blue")
u.speak

echo "Making copy of a as u; colors and types should match."
u.deepCopy(a)
u.speak
a.speak

echo "Assigning new color to u; A's color should be unchanged."
u.myValue = "Orange"
u.speak
a.speak

echo "Assigning u to reference same object as b; colors and types should match."
u = b
u.speak
b.speak

echo "Assigning new color to u. Since u,b reference the same object, b's color changes as well."
u.myValue = "Yellow"
u.speak
b.speak


@interface T : NSObject
- (void)identify;
@end

@implementation T
- (void)identify {
    NSLog(@"I am a genuine T");
}
- (id)copyWithZone:(NSZone *)zone {
    T *copy = [[[self class] allocWithZone:zone] init]; // call an appropriate constructor here
                                                        // then copy data into it as appropriate here
                                                        // make sure to use "[[self class] alloc..." and
                                                        // not "[T alloc..." to make it polymorphic
    return copy;
}
@end

@interface S : T
@end

@implementation S
- (void)identify
{
    NSLog(@"I am an S");
}
@end

int main()
{
    @autoreleasepool {

        T *original = [[S alloc] init];
        T *another = [original copy];
        [another identify]; // logs "I am an S"

    }
    return 0;
}


function love.load ()
    love.window.setTitle("Polyspiral")
    incr = 0
end

function love.update (dt)
    incr = (incr + 0.05) % 360
    x1 = love.graphics.getWidth() / 2
    y1 = love.graphics.getHeight() / 2
    length = 5
    angle = incr
end

function love.draw ()
    for i = 1, 150 do
        x2 = x1 + math.cos(angle) * length
        y2 = y1 + math.sin(angle) * length
        love.graphics.line(x1, y1, x2, y2)
        x1, y1 = x2, y2
        length = length + 3
        angle = (angle + incr) % 360
    end
end


linedata = {};
Dynamic[Graphics[Line[linedata], PlotRange -> 1000]]
Do[
 linedata = AnglePath[{#, \[Theta]} & /@ Range[5, 300, 3]];
 Pause[0.1];
 ,
 {\[Theta], Subdivide[0.1, 1, 100]}
]


# Pendulum simulation.

import math, random

import gintro/[gobject, gdk, gtk, gio, glib, cairo]

const
  Width = 500
  Height = 500
  DrawIters = 72
  Red = [float 1, 0, 0]
  Green = [float 0, 1, 0]
  Blue = [float 0, 0, 1]
  Black = [float 0, 0, 0]
  White = [float 255, 255, 255]
  Gold = [float 255, 215, 0]
  Colors = [Blue, Red, Green, White, Gold]
  Angles = [75, 100, 135, 160]

type

  Vec2 = tuple[x, y: float]
  Point = Vec2

  # Description of the simulation.
  Simulation = ref object
    area: DrawingArea
    xmax, ymax: float
    center: Point
    itercount: int

#---------------------------------------------------------------------------------------------------

proc newSimulation(area: DrawingArea; width, height: int): Simulation {.noInit.} =
  ## Allocate and initialize the simulation object.

  new(result)
  result.area = area
  result.xmax = float(width - 1)
  result.ymax = float(height - 1)
  result.center = (result.xmax * 0.5, result.ymax * 0.5)

#---------------------------------------------------------------------------------------------------

func δ(r, θ: float): Vec2 = (r * cos(degToRad(θ)), r * sin(degToRad(θ)))

#---------------------------------------------------------------------------------------------------

func nextPoint(p: Point; r, θ: float): Point =
  let dp = δ(r, θ)
  result = (p.x + dp.x, p.y + dp.y)

#---------------------------------------------------------------------------------------------------

proc draw(sim: Simulation; context: cairo.Context) =
  ## Draw the spiral.

  context.setSource(Black)
  context.rectangle(0, 0, sim.xmax, sim.ymax)
  context.fill()

  let colorIndex = sim.itercount mod Colors.len
  let color = Colors[colorIndex]

  var p1 = sim.center
  let δθ = Angles[sim.itercount mod Angles.len].toFloat
  var θ = δθ * rand(1.0) * 3
  var r = 5.0
  let δr = 3.0

  for _ in 1..DrawIters:
    let p2 = p1.nextPoint(r, θ)
    context.moveTo(p1.x, p1.y)
    context.setSource(color)
    context.lineTo(p2.x, p2.y)
    context.setLineWidth(2)
    context.stroke()
    θ += δθ
    r += δr
    p1 = p2

#---------------------------------------------------------------------------------------------------

proc update(sim: Simulation): gboolean =
  ## Update the simulation state.

  result = gboolean(1)
  sim.draw(sim.area.window.cairoCreate())
  inc sim.itercount

#---------------------------------------------------------------------------------------------------

proc activate(app: Application) =
  ## Activate the application.

  let window = app.newApplicationWindow()
  window.setSizeRequest(Width, Height)
  window.setTitle("Polyspiral")

  let area = newDrawingArea()
  window.add(area)

  let sim = newSimulation(area, Width, Height)

  timeoutAdd(500, update, sim)

  window.showAll()

#———————————————————————————————————————————————————————————————————————————————————————————————————

let app = newApplication(Application, "Rosetta.polyspiral")
discard app.connect("activate", activate)
discard app.run()


.model small
.stack 1024
.data                    ; data segment begins here
UserRam byte 256 dup (0) ; the next 256 bytes have a value of zero. The address of the 0th of these bytes can be referenced as "UserRam"

tempByte equ UserRam     ;this variable's address is the same as that of the 0th byte of UserRam
tempWord equ UserRam+2   ;this variable's address is the address of UserRam + 2
.code
start:
mov ax, @data
mov ds, ax

mov ax, @code
mov es, ax


myVar equ $100000    ; a section of user ram given a label
myData:              ; a data table given a label
   dc.b $80,$81,$82,$83


type Int_Access is access Integer;
Int_Acc : Int_Access := new Integer'(5);


let obj1 =
  object
    method name = "T"
  end

let obj2 =
  object
    method name = "S"
  end

let () =
  print_endline (Oo.copy obj1)#name; (* prints "T" *)
  print_endline (Oo.copy obj2)#name; (* prints "S" *)


s = .s~new
s2 = s~copy   -- makes a copy of the first
if s == s2 then say "copy didn't work!"
if s2~name == "S" then say "polymorphic copy worked"

::class t
::method name
  return "T"

::class s subclass t
::method name
  return "S"


'======
class T
'======

float vv

method constructor(float a=0) {vv=a}
method destructor    {}
method copy as T     {new T ob : ob<=vv : return ob}
method mA() as float {return vv*2}
method mB() as float {return vv*3}

end class

'======
class S
'======

has T

method mB() as float {return vv*4} 'ovveride

end class

'====
'TEST
'====

new T objA(10.5)

let objB = cast S objA.copy

print objA.mb 'result 31.5
print objB.mb 'result 42

del objA : del objB


declare
  class T from ObjectSupport.reflect
     meth init
        skip
     end

     meth name($)
        'T'
     end
  end

  class S from T
     attr a
     feat f

     meth name($)
        'S'
     end

     meth getA($) @a end
     meth setA(V) a := V end
  end

  Obj = {New S init}
  Copy = {Obj clone($)}
in
  %% Some assertions:

  %% Copy is really an S:
  {Copy name($)} = 'S'

  %% Copy is not just a reference to the same object:
  {System.eq Obj Copy} = false

  %% Not a deep copy. Feature f has the same identity for both objects:
  {System.eq Obj.f Copy.f} = true

  %% However, both have their own distinct attributes:
  {Obj setA(13)}
  {Copy setA(14)}
  {Obj getA($)} \= {Copy getA($)} = true


\\ Plot the line from x1,y1 to x2,y2.
plotline(x1,y1,x2,y2,w=0)={plotmove(w, x1,y1);plotrline(w,x2-x1,y2-y1);}
\\ Convert degrees to radians.
rad2(degs)={return(degs*Pi/180.0)}
\\ Convert Polar coordinates to Cartesian.
cartes2(r,a,rndf=0)={my(v,x,y); x=r*cos(a); y=r*sin(a);
  if(rndf==0, return([x,y]), return(round([x,y])))}


#!/usr/bin/perl

use strict; # https://rosettacode.org/wiki/Polyspiral
use warnings;
use Tk;
use List::Util qw( min );

my $size = 500;
my ($width, $height, $x, $y, $dist);
my $angleinc = 0;
my $active = 0;
my $wait = 1000 / 30;
my $radian = 90 / atan2 1, 0;

my $mw = MainWindow->new;
$mw->title( 'Polyspiral' );
my $c = $mw->Canvas( -width => $size, -height => $size,
  -relief => 'raised', -borderwidth => 2,
  )->pack(-fill => 'both', -expand => 1);
$mw->bind('<Configure>' => sub { $width = $c->width; $height = $c->height;
  $dist = min($width, $height) ** 2 / 4 } );
$mw->Button(-text => $_->[0], -command => $_->[1],
  )->pack(-side => 'right') for
  [ Exit => sub {$mw->destroy} ],
  [ 'Start / Pause' => sub { $active ^= 1; step() } ];

MainLoop;
-M $0 < 0 and exec $0;

sub step
  {
  $active or return;
  my @pts = ($x = $width >> 1, $y = $height >> 1);
  my $length = 5;
  my $angle = $angleinc;
  $angleinc += 0.05 / $radian;
  while( ($x - $width / 2)**2 + ($y - $height / 2)**2 < $dist && @pts < 300 )
    {
    push @pts, $x, $y;
    $x += $length * cos($angle);
    $y += $length * sin($angle);
    $length += 3;
    $angle += $angleinc;
    }
  $c->delete('all');
  $c->createLine( @pts );
  $mw->after($wait => \&step);
  }


;this example uses VASM syntax, your assembler may not use the # before constants or the semicolon for comments
MOV R1,#0x04000000
MOV R0,#0x403
STR R0,[R1] ;store 0x403 into memory address 0x04000000.


VarSetCapacity(var, 100)   ; allocate memory
NumPut(87, var, 0, "Char") ; store 87 at offset 0
MsgBox % NumGet(var, 0, "Char") ; get character at offset 0 (87)
MsgBox % &var   ; address of contents pointed to by var structure
MsgBox % *&var ; integer at address of var contents  (87)


      REM Pointer to integer variable:
      pointer_to_varA = ^varA%
      !pointer_to_varA = 123456
      PRINT !pointer_to_varA

      REM Pointer to variant variable:
      pointer_to_varB = ^varB
      |pointer_to_varB = PI
      PRINT |pointer_to_varB

      REM Pointer to procedure:
      PROCmyproc : REM conventional call to initialise
      pointer_to_myproc = ^PROCmyproc
      PROC(pointer_to_myproc)

      REM Pointer to function:
      pointer_to_myfunc = ^FNmyfunc
      PRINT FN(pointer_to_myfunc)
      END

      DEF PROCmyproc
      PRINT "Executing myproc"
      ENDPROC

      DEF FNmyfunc
      = "Returned from myfunc"


package T;
sub new {
        my $cls = shift;
        bless [ @_ ], $cls
}

sub set_data {
        my $self = shift;
        @$self = @_;
}

sub copy {
        my $self = shift;
        bless [ @$self ], ref $self;
}

sub manifest {
        my $self = shift;
        print "type T, content: @$self\n\n";
}

package S;
our @ISA = 'T';
# S is inheriting from T.
# 'manifest' method is overriden, while 'new', 'copy' and
# 'set_data' are all inherited.
sub manifest {
        my $self = shift;
        print "type S, content: @$self\n\n";
}

package main;

print "# creating \$t as a T\n";
my $t = T->new('abc');
$t->manifest;

print "# creating \$s as an S\n";
my $s = S->new('SPQR');
$s->manifest;

print "# make var \$x as a copy of \$t\n";
my $x = $t->copy;
$x->manifest;

print "# now as a copy of \$s\n";
$x = $s->copy;
$x->manifest;

print "# show that this copy is indeed a separate entity\n";
$x->set_data('totally different');
print "\$x is: ";
$x->manifest;


with javascript_semantics
enum NAME, METHOD

procedure me_t()
    puts(1,"I is a T\n")
end procedure

procedure me_s()
    puts(1,"I is an S\n")
end procedure

type T(object o)
    -- as o[METHOD] can be overidden, don't verify it (as in test for me_t)!
    return sequence(o) and length(o)=2 and string(o[NAME]) and integer(o[METHOD])
end type

type S(T t)
    return t[METHOD] = me_s
end type

S s = {"S",me_s}
T t = {"T",me_t}

call_proc(t[METHOD],{})
t = s
call_proc(t[METHOD],{})


--
-- demo\rosetta\Polyspiral.exw
-- ===========================
--
-- Space toggles the timer, '+' increases speed (up to 100 FPS), '-' decreases speed
-- 'M' toggles "mod360", which inverts the angle every 360/2PI or so, since sin/cos
-- accept arguments in radians not degrees (and mod 2*PI changes nothing), producing
-- non-true polyspirals, but quite interesting nevertheless.
--
with javascript_semantics
constant TITLE = "Polyspiral"
include pGUI.e

Ihandle dlg, canvas, timer
cdCanvas cddbuffer, cdcanvas
atom incr = 0
bool mod360 = false

procedure Polyspiral(atom x1, y1)
    atom angle = incr
    integer len = 5
    incr += 0.05
    if mod360 then
        incr = mod(incr,360)
    end if
    for i=1 to 150 do
        atom x2 = x1 + cos(angle)*len,
             y2 = y1 + sin(angle)*len
        cdCanvasSetForeground(cddbuffer, i*#200+i*#40+i*#10)
        cdCanvasLine(cddbuffer, x1, y1, x2, y2)
        {x1, y1} = {x2, y2}
        len += 3
        angle += incr
        if mod360 then
            angle = mod(angle,360)
        end if
    end for
end procedure

function redraw_cb(Ihandle /*ih*/)
    integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE")
    cdCanvasActivate(cddbuffer)
    cdCanvasClear(cddbuffer)
    Polyspiral(w/2, h/2)
    cdCanvasFlush(cddbuffer)
    integer ms = IupGetInt(timer,"TIME")
    IupSetStrAttribute(dlg, "TITLE", "%s (timer=%d [%g FPS], angle %3.2f%s)",
                       {TITLE,ms,1000/ms,incr,iff(mod360?" (mod360)":"")})
    return IUP_DEFAULT
end function

function timer_cb(Ihandle /*timer*/)
    IupUpdate(canvas)
    return IUP_IGNORE
end function

function map_cb(Ihandle canvas)
    cdcanvas = cdCreateCanvas(CD_IUP, canvas)
    cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
    cdCanvasSetBackground(cddbuffer, CD_WHITE)
    cdCanvasSetForeground(cddbuffer, CD_GRAY)
    return IUP_DEFAULT
end function

function key_cb(Ihandle /*ih*/, atom c)
    if c=K_ESC then return IUP_CLOSE end if
    if c=' ' then
        IupSetInt(timer,"RUN",not IupGetInt(timer,"RUN"))
    elsif find(c,"+-") then
        IupSetInt(timer,"RUN",false)
        c = -(','-c) -- ('+' ==> +1, '-' ==> -1)
        IupSetInt(timer,"TIME",max(10,IupGetInt(timer,"TIME")+c*10))
        IupSetInt(timer,"RUN",true)
    elsif upper(c)='M' then
        mod360 = not mod360
    end if
    return IUP_CONTINUE
end function

IupOpen()
canvas = IupCanvas("RASTERSIZE=640x640")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
                         "ACTION", Icallback("redraw_cb")})
timer = IupTimer(Icallback("timer_cb"), 20)
dlg = IupDialog(canvas,`TITLE="%s"`, {TITLE})
IupSetCallback(dlg, "KEY_CB", Icallback("key_cb"))
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL)
if platform()!=JS then
    IupMainLoop()
    IupClose()
end if


static void Main(string[] args)
{
	int p;

	p = 1;
	Console.WriteLine("Ref Before: " + p);
	Value(ref p);
	Console.WriteLine("Ref After : " + p);

	p = 1;
	Console.WriteLine("Val Before: " + p);
	Value(p);
	Console.WriteLine("Val After : " + p);

	Console.ReadLine();
}

private static void Value(ref int Value)
{
	Value += 1;
}
private static void Value(int Value)
{
	Value += 1;
}


       01  ptr                     USAGE POINTER TO Some-Type.
       01  prog-ptr                USAGE PROGRAM-POINTER "some-program". *> TO is optional


<?php
class T {
      function name() { return "T"; }
}

class S {
      function name() { return "S"; }
}

$obj1 = new T();
$obj2 = new S();
$obj3 = clone $obj1;
$obj4 = clone $obj2;
echo $obj3->name(), "\n"; // prints "T"
echo $obj4->name(), "\n"; // prints "S"
?>


import copy

class T:
   def classname(self):
      return self.__class__.__name__

   def __init__(self):
      self.myValue = "I'm a T."

   def speak(self):
      print self.classname(), 'Hello', self.myValue

   def clone(self):
      return copy.copy(self)

class S1(T):
   def speak(self):
      print self.classname(),"Meow", self.myValue

class S2(T):
   def speak(self):
      print self.classname(),"Woof", self.myValue

print "creating initial objects of types S1, S2, and T"
a = S1()
a.myValue = 'Green'
a.speak()

b = S2()
b.myValue = 'Blue'
b.speak()

u = T()
u.myValue = 'Purple'
u.speak()

print "Making copy of a as u, colors and types should match"
u = a.clone()
u.speak()
a.speak()
print "Assigning new color to u, A's color should be unchanged."
u.myValue = "Orange"
u.speak()
a.speak()

print "Assigning u to reference same object as b, colors and types should match"
u = b
u.speak()
b.speak()
print "Assigning new color to u. Since u,b references same object b's color changes as well"
u.myValue = "Yellow"
u.speak()
b.speak()


import math

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((1024, 600))

pygame.display.set_caption("Polyspiral")

incr = 0

running = True

while running:
	pygame.time.Clock().tick(60)
	for event in pygame.event.get():
		if event.type==QUIT:
			running = False
			break

	incr = (incr + 0.05) % 360
	x1 = pygame.display.Info().current_w / 2
	y1 = pygame.display.Info().current_h / 2
	length = 5
	angle = incr

	screen.fill((255,255,255))

	for i in range(1,151):
		x2 = x1 + math.cos(angle) * length
		y2 = y1 + math.sin(angle) * length
		pygame.draw.line(screen, (255,0,0), (x1, y1), (x2, y2), 1)
		# pygame.draw.aaline(screen, (255,0,0), (x1, y1), (x2, y2)) # Anti-Aliased
		x1, y1 = x2, y2
		length += 3
		angle = (angle + incr) % 360

	pygame.display.flip()


#lang racket

(require 2htdp/universe pict racket/draw)

(define ((polyspiral width height segment-length-increment n-segments) tick/s/28)
  (define turn-angle (degrees->radians (/ tick/s/28 8)))
  (pict->bitmap
   (dc (λ (dc dx dy)
         (define old-brush (send dc get-brush))
         (define old-pen (send dc get-pen))
         (define path (new dc-path%))
         (define x (/ width #i2))
         (define y (/ height #i2))
         (send path move-to x y)
         (for/fold ((x x) (y y) (l segment-length-increment) (a #i0))
                   ((seg n-segments))
           (define x′ (+ x (* l (cos a))))
           (define y′ (+ y (* l (sin a))))
           (send path line-to x y)
           (values x′ y′ (+ l segment-length-increment) (+ a turn-angle)))
         (send dc draw-path path dx dy)
         (send* dc (set-brush old-brush) (set-pen old-pen)))
       width height)))

(animate (polyspiral 400 400 2 1000))


void main() {
    // Take the address of 'var' and placing it in a pointer:
    int var;
    int* ptr = &var;

    // Take the pointer to the first item of an array:
    int[10] data;
    auto p2 = data.ptr;

    // Depending on variable type, D will automatically pass either
    // by value or reference.
    // By value: structs, statically sized arrays, and other
    //           primitives (int, char, etc...);
    // By reference: classes;
    // By kind of reference: dynamically sized arrays, array slices.

    struct S {}
    class C {}

    void foo1(S s) {}        // By value.
    void foo2(C c) {}        // By reference.
    void foo3(int i) {}      // By value.
    void foo4(int[4] i) {}   // By value (unlike C).
    void foo6(int[] i) {}    // Just length-pointer struct by value.
    void foo5(T)(ref T t) {} // By reference regardless of what type
                             // T really is.
}


#lang racket/base

(define (copy-prefab-struct str)
  (apply make-prefab-struct (vector->list (struct->vector str))))

(struct point (x y) #:prefab)
(struct point/color point (color) #:prefab)

(let* ([original (point 0 0)]
       [copied (copy-prefab-struct original)])
  (displayln copied)
  (displayln (eq? original copied)))

(let* ([original (point/color 0 0 'black)]
       [copied (copy-prefab-struct original)])
  (displayln copied)
  (displayln (eq? original copied)))


my Cool $x = 22/7 but role Fink { method brag { say "I'm a cool {self.WHAT.raku}!" }}
my Cool $y = $x.clone;
$y.brag;


/*REXX program to  copy  (polymorphically)  one variable's value into another variable. */
b= 'old value.'
a= 123.45
b= a                                             /*copy a variable's value into another.*/
if a==b  then say "copy did work."
         else say "copy didn't work."            /*didn't work, maybe ran out of storage*/
                                                 /*stick a fork in it,  we're all done. */


class T
  def name
    "T"
  end
end

class S
  def name
    "S"
  end
end

obj1 = T.new
obj2 = S.new
puts obj1.dup.name # prints "T"
puts obj2.dup.name # prints "S"


object PolymorphicCopy {

  def main(args: Array[String]) {
    val a: Animal = Dog("Rover", 3, "Terrier")
    val b: Animal = a.copy() // calls Dog.copy() because runtime type of 'a' is Dog
    println(s"Dog 'a' = $a") // implicitly calls Dog.toString()
    println(s"Dog 'b' = $b") // ditto
    println(s"Dog 'a' is ${if (a == b) "" else "not"} the same object as Dog 'b'")
  }

  case class Animal(name: String, age: Int) {

    override def toString = s"Name: $name, Age: $age"
  }

  case class Dog(override val name: String, override val age: Int, breed: String) extends Animal(name, age) {

    override def toString = super.toString() + s", Breed: $breed"
  }

}


# Project : Polyspiral

load "guilib.ring"

paint = null
incr = 1
x1 = 1000
y1 = 1080
angle = 10
length = 10

new qapp
        {
        win1 = new qwidget() {
                  setwindowtitle("")
                  setgeometry(10,10,1000,1080)
                  label1 = new qlabel(win1) {
                              setgeometry(10,10,1000,1080)
                              settext("")
                  }
                  new qpushbutton(win1) {
                          setgeometry(150,30,100,30)
                          settext("draw")
                          setclickevent("draw()")
                  }
                  show()
        }
        exec()
        }

func draw
        p1 = new qpicture()
               color = new qcolor() {
               setrgb(0,0,255,255)
        }
        pen = new qpen() {
                 setcolor(color)
                 setwidth(1)
        }
        paint = new qpainter() {
                  begin(p1)
                  setpen(pen)
        for i = 1 to 150
             x2 = x1 + cos(angle) * length
             y2 = y1 + sin(angle) * length
             drawline(x1, y1, x2, y2)
             x1 = x2
             y1 = y2
             length = length + 3
             angle = (angle + incr) % 360
        next

        endpaint()
        }
        label1 { setpicture(p1) show() }


import java.awt._
import java.awt.event.ActionEvent

import javax.swing._

object PolySpiral extends App {

  SwingUtilities.invokeLater(() =>
    new JFrame("PolySpiral") {

      class PolySpiral extends JPanel {
        private var inc = 0.0

        override def paintComponent(gg: Graphics): Unit = {
          val g = gg.asInstanceOf[Graphics2D]
          def drawSpiral(g: Graphics2D, l: Int, angleIncrement: Double): Unit = {
            var len = l
            var (x1, y1) = (getWidth / 2d, getHeight / 2d)
            var angle = angleIncrement
            for (i <- 0 until 150) {
              g.setColor(Color.getHSBColor(i / 150f, 1.0f, 1.0f))
              val x2 = x1 + math.cos(angle) * len
              val y2 = y1 - math.sin(angle) * len
              g.drawLine(x1.toInt, y1.toInt, x2.toInt, y2.toInt)
              x1 = x2
              y1 = y2
              len += 3
              angle = (angle + angleIncrement) % (math.Pi * 2)
            }
          }

          super.paintComponent(gg)
          g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
          drawSpiral(g, 5, math.toRadians(inc))
        }

        setBackground(Color.white)
        setPreferredSize(new Dimension(640, 640))

        new Timer(40, (_: ActionEvent) => {
          inc = (inc + 0.05) % 360
          repaint()
        }).start()
      }

      add(new PolySpiral, BorderLayout.CENTER)
      pack()
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
      setLocationRelativeTo(null)
      setResizable(true)
      setVisible(true)
    }
  )

}


var x := 0
def slot := &x # define "slot" to be x's slot

x := 1         # direct assignment; value is now 1
slot.put(2)    # via slot object; value is now 2


(define B (box 42))
    → B ;; box reference
(unbox B)
    → 42 ;; box contents

;; sets new value for box contents
(define ( change-by-ref abox avalue)
    (set-box! abox avalue) )

(change-by-ref B 666)
    → #[box 666]
(unbox B)
    → 666


 variable myvar   \ stores 1 cell
 fvariable myfvar \ stores 1 floating point number (often 8 bytes)
 2variable my2var \ stores 2 cells


class T(value) {
    method display {
        say value;
    }
}

class S(value) < T {
    method display {
        say value;
    }
}

var obj1 = T("T");
var obj2 = S("S");
var obj3 = obj2.dclone;         # make a deep clone of obj2

obj1.value = "foo";             # change the value of obj1
obj2.value = "bar";             # change the value of obj2

obj1.display;                   # prints "foo"
obj2.display;                   # prints "bar"
obj3.display;                   # prints "S"


define: #T &parents: {Cloneable}.

define: #S &parents: {Cloneable}.

define: #obj1 -> T clone.
define: #obj2 -> S clone.

obj1 printName.
obj2 printName.


class T {
  required init() { } // constructor used in polymorphic initialization must be "required"
  func identify() {
    println("I am a genuine T")
  }
  func copy() -> T {
    let newObj : T = self.dynamicType() // call an appropriate constructor here
    // then copy data into newObj as appropriate here
    // make sure to use "self.dynamicType(...)" and
    // not "T(...)" to make it polymorphic
    return newObj
  }
}

class S : T {
  override func identify()  {
    println("I am an S")
  }
}

let original : T = S()
let another : T = original.copy()
println(original === another) // prints "false" (i.e. they are different objects)
another.identify() // prints "I am an S"


class Animal {
    construct new(name, age) {
        _name = name
        _age = age
    }

    name { _name }
    age  { _age }

    copy() { Animal.new(name, age) }

    toString { "Name: %(_name), Age: %(_age)" }
}

class Dog is Animal {
    construct new(name, age, breed) {
        super(name, age) // call Animal's constructor
        _breed = breed
    }

    // name and age properties will be inherited from Animal
    breed { _breed }

    copy() { Dog.new(name, age, breed) } // overrides Animal's copy() method

    toString { super.toString + ", Breed: %(_breed)" } // overrides Animal's toString method
}

var a = Dog.new("Rover", 3, "Terrier") // a's type is Dog
var b = a.copy() // a's copy() method is called and so b's type is Dog
System.print("Dog 'a' -> %(a)") // implicitly calls a's toString method
System.print("Dog 'b' -> %(b)") // ditto
System.print("Dog 'a' is %((Object.same(a, b)) ? "" : "not") the same object as Dog 'b'")


width,height = #.scrsize()
#.angle(#.degrees)
#.scroff()
incr = 0
>
  incr = (incr+0.05)%360
  x = width/2
  y = height/2
  length = 5
  angle = incr
  #.scrclear()
  #.drawline(x,y,x,y)
  > i, 1..150
    x += length*#.cos(angle)
    y += length*#.sin(angle)
    #.drawcolor(#.hsv2rgb(angle,1,1):3)
    #.drawline(x,y)
    length += 3
    angle = (angle+incr)%360
  <
  #.scr()
<


<svg viewBox="0 0 100 100" stroke="#000" stroke-width="0.3">
  <g>
    <line x1="50" y1="50" x2="54" y2="50"></line>
    <animateTransform attributeName="transform" type="rotate" from="-120 50 50" to="240 50 50" dur="2400s" repeatCount="indefinite"></animateTransform>
    <g>
      <line x1="54" y1="50" x2="58.16" y2="50"></line>
      <animateTransform attributeName="transform" type="rotate" from="-120 54 50" to="240 54 50" dur="2400s" repeatCount="indefinite"></animateTransform>
      <g>
        <line x1="58.16" y1="50" x2="62.48639" y2="50"></line>
        <animateTransform attributeName="transform" type="rotate" dur="2400s" repeatCount="indefinite" to="240 58.16 50" from="-120 58.16 50"></animateTransform>

        <!-- ad nauseam -->

      </g>
    </g>
  </g>
</svg>


import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math

var Radians = Fn.new { |d| d * Num.pi / 180 }

class Polyspiral {
    construct new(width, height) {
        Window.title = "Polyspiral"
        Window.resize(width, height)
        Canvas.resize(width, height)
        _w = width
        _h = height
        _inc = 0
    }

    init() {
        drawSpiral(5, Radians.call(_inc))
    }

    drawSpiral(length, angleIncrement) {
        Canvas.cls(Color.white)
        var x1 = _w / 2
        var y1 = _h / 2
        var len = length
        var angle = angleIncrement
        for (i in 0...150) {
            var col = Color.hsv(i / 150 * 360, 1, 1)
            var x2 = x1 + Math.cos(angle) * len
            var y2 = y1 - Math.sin(angle) * len
            Canvas.line(x1.truncate, y1.truncate, x2.truncate, y2.truncate, col)
            x1 = x2
            y1 = y2
            len = len + 3
            angle = (angle + angleIncrement) % (Num.pi * 2)
        }
    }

    update() {
        _inc = (_inc + 0.05) % 360
    }

    draw(alpha) {
        drawSpiral(5, Radians.call(_inc))
    }
}

var Game = Polyspiral.new(640, 640)


' FB 1.05.0 Win64

Type Cat
  name As String
  age As Integer
End Type

Type CatInfoType As Sub (As Cat Ptr)

Sub printCatInfo(c As Cat Ptr)
  Print "Name "; c->name, "Age"; c-> age
  Print
End Sub

' create Cat object on heap and store a pointer to it
Dim c As Cat Ptr = New Cat

' set fields using the pointer and the "crow's foot" operator
c->name = "Fluffy"
c->age = 9

' print them out through a procedure pointer
Dim cit As CatInfoType = ProcPtr(printCatInfo)
cit(c)

Delete c
c = 0

Dim i As Integer = 3
' create an integer pointer variable and set it to the address of 'i'
Dim pi As Integer Ptr = @i

'change the variable through the pointer
*pi = 4

'print out the result
print "i ="; *pi

'create a reference to the variable i
Dim ByRef As Integer j = i

' set j (and hence i) to a new value
j = 5

' print them out
Print "i ="; i, "j ="; j
Sleep


var p *int  // declare p to be a pointer to an int
i = &p      // assign i to be the int value pointed to by p


import Data.STRef

example :: ST s ()
example = do
  p <- newSTRef 1
  k <- readSTRef p
  writeSTRef p (k+1)


 public class Foo { public int x = 0; }

 void somefunction() {
     Foo a; // this declares a reference to Foo object; if this is a class field, it is initialized to null
     a = new Foo(); // this assigns a to point to a new Foo object
     Foo b = a; // this declares another reference to point to the same object that "a" points to
     a.x = 5; // this modifies the "x" field of the object pointed to by "a"
     System.out.println(b.x); // this prints 5, because "b" points to the same object as "a"
 }


def  Width=640., Height=480.;
def  Deg2Rad = 3.141592654/180.;
real Incr, Angle, Length, X, Y, X1, Y1;
int  N;
[SetVid($101);  \VESA 640x480x8 graphics
Incr:= 0.;
repeat  Incr:= Incr+1.;
        X:= Width/2.;  Y:= Height/2.;
        Move(fix(X), fix(Y));
        Length:= 5.;
        Angle:= Incr;
        for N:= 1 to 150 do
            [X1:= X + Length*Cos(Angle*Deg2Rad);
             Y1:= Y + Length*Sin(Angle*Deg2Rad);
             Line(fix(X1), fix(Y1), N+16);
             X:= X1;  Y:= Y1;
             Length:= Length+3.;
             Angle:= Angle+Incr;
            ];
        DelayUS(83_333);
        Clear;
until   KeyHit;
]


w = 1024 : h = 600
open window w, h
color 255,0,0

incr = 0 : twopi = 2 * pi

while true
    incr = mod(incr + 0.05, twopi)
    x1 = w / 2
    y1 = h / 2
    length = 5
    angle = incr

    clear window

    for i = 1 to 151
        x2 = x1 + cos(angle) * length
        y2 = y1 + sin(angle) * length
        line x1, y1, x2, y2
        x1 = x2 : y1 = y2
        length = length + 3
        angle = mod(angle + incr, twopi)
    next
    pause 1
end while


w,h:=640,640;
bitmap:=PPM(w,h,0xFF|FF|FF);  // White background
angleIncrement:=(3.0).toRad();
while(True){
   r,angle:=0.0, 0.0;
   ao,len,inc:=w/2, 2.5, angleIncrement+(130.0).toRad();
   foreach c in (128){
      s,a:=r + len, angle + inc;
      x,y:=r.toRectangular(angle);
      u,v:=r.toRectangular(a);
      c=c.shiftLeft(21) + c.shiftLeft(10) + c*8;  // convert c to a RGB
      bitmap.line(ao+x,ao+y, ao+u,ao+v, c);
      r,angle=s,a;
   }
   bitmap.writeJPGFile("polyspiral.zkl.jpg");
   bitmap.fill(0xFF|FF|FF);  // White background
   angleIncrement=(angleIncrement + 0.05);
   Atomic.sleep(3);
}


x = [1, 2, 3, 7]

parr = pointer(x)

xx = unsafe_load(parr, 4)

println(xx)  #  Prints 7


// Kotlin Native v0.3

import kotlinx.cinterop.*

fun main(args: Array<String>) {
    // allocate space for an 'int' on the native heap and wrap a pointer to it in an IntVar object
    val intVar: IntVar = nativeHeap.alloc<IntVar>()
    intVar.value = 3                 // set its value
    println(intVar.value)            // print it
    println(intVar.ptr)              // corresponding CPointer object
    println(intVar.rawPtr)           // the actual address wrapped by the CPointer

    // change the value and print that
    intVar.value = 333
    println()
    println(intVar.value)
    println(intVar.ptr)              // same as before, of course

    // implicitly convert to an opaque pointer which is the supertype of all pointer types
    val op: COpaquePointer = intVar.ptr

    // cast opaque pointer to a pointer to ByteVar
    println()
    var bytePtr: CPointer<ByteVar> = op.reinterpret<ByteVar>()
    println(bytePtr.pointed.value)   // value of first byte i.e. 333 - 256 = 77 on Linux
    bytePtr = (bytePtr + 1)!!        // increment pointer
    println(bytePtr.pointed.value)   // value of second byte i.e. 1 on Linux
    println(bytePtr)                 // one byte more than before
    bytePtr = (bytePtr + (-1))!!     // decrement pointer
    println(bytePtr)                 // back to original value
    nativeHeap.free(intVar)          // free native memory

    // allocate space for an array of 3 'int's on the native heap
    println()
    var intArray: CPointer<IntVar> = nativeHeap.allocArray<IntVar>(3)
    for (i in 0..2) intArray[i] = i  // set them
    println(intArray[2])             // print the last element
    nativeHeap.free(intArray)        // free native memory
}


local table1 = {1,2,3}
local table2 = table1
table2[3] = 4
print(unpack(table1))


A=10
Module Beta {
      Read &X
      X++
}
Beta &A
Print A=11


TYPE IntRef = REF INTEGER;

VAR intref := NEW(IntRef);

intref^ := 10


type Foo = ref object
  x, y: float

var f: Foo
new f


let p = ref 1;; (* create a new "reference" data structure with initial value 1 *)
let k = !p;;    (* "dereference" the reference, returning the value inside *)
p := k + 1;;    (* set the value inside to a new value *)


 ::class Foo
 ::method init
   expose x
   x = 0
 ::attribute x

 ::routine somefunction
     a = .Foo~new   -- assigns a to point to a new Foo object
     b = a          -- b and a now point to the same object
     a~x = 5        -- modifies the X variable inside the object pointer to by a
     say b~x        -- displays "5" because b points to the same object as a


n=1;
issquare(9,&n);
print(n); \\ prints 3


program pointerDemo;

type
	{
		A new pointer data type is declared by `↑` followed by a data type name,
		the domain.

		The domain data type may not have been declared yet, but must be
		declared within the current `type` section.

		Most compilers do not support the reference token `↑` as specified in
		the ISO standards 7185 and 10206, but use the alternative `^` (caret).
	}
	integerReference = ^integer;

var
	integerLocation: integerReference;

begin
	{
		The procedure `new` taken one pointer variable and allocates memory for
		one new instance of the pointer domain’s data type (here an `integer`).
		The pointer variable will hold the address of the allocated instance.
	}
	new(integerLocation);

	{
		Dereferencing a pointer is done via appending `↑` to the variable’s
		name. All operations on the domain type are now possible.
	}
	integerLocation^ := 42;

	{
		The procedure `dispose` takes one pointer variable and releases the
		underlying memory. The supplied variable is otherwise not modified.
	}
	dispose(integerLocation);
	{
		In Pascal, `dispose` is not necessary. Any excess memory is automatically
		released after `program` termination.
	}
end.


 # start with some var definitions
 my $scalar = 'aa';
 my @array = ('bb', 'cc');
 my %hash = ( dd => 'DD', ee => 'EE' );

 # make references
 my $scalarref = \$scalar;
 my $arrayref = \@array;
 my $hashref = \%hash;


atom addr = allocate(8) -- (assumes 32 bit)
poke4(addr,{NULL,SOME_CONSTANT})
c_proc(xSome_External_Routine,{addr,addr+4})
?peek4s({addr,2})   -- prints {x,y}
free(addr)


<?php
/* Assignment of scalar variables */
$a = 1;
$b =& $a; // $b and $a are now linked together
$b = 2; //both $b and $a now equal 2
$c = $b;
$c = 7; //$c is not a reference; no change to $a or $b
unset($a); //won't unset $b, just $a.

/* Passing by Reference in and out of functions */
function &pass_out() {
    global $filestr;  //$exactly equivalent to: $filestr =& $_GLOBALS['filestr'];

    $filestr = get_file_contents("./bigfile.txt");
    return $_GLOBALS['filestr'];
}
function pass_in(&$in_filestr) {
    echo "File Content Length: ". strlen($in_filestr);

    /* Changing $in_filestr also changes the global $filestr and $tmp */
    $in_filestr .= "EDIT";
    echo "File Content Length is now longer: ". strlen($in_filestr);
}

$tmp = &pass_out(); // now $tmp and the global variable $filestr are linked
pass_in($tmp); // changes $tmp and prints the length

?>


: (setq L (1 a 2 b 3 c))         # Create a list of 6 items in 'L'
-> (1 a 2 b 3 c)

: (nth L 4)                      # Get a pointer to the 4th item
-> (b 3 c)

: (set (nth L 4) "Hello")        # Store "Hello" in that location
-> "Hello"

: L                              # Look at the modified list in 'L'
-> (1 a 2 "Hello" 3 c)


dcl i fixed bin(31);
dcl p pointer;
dcl j fixed bin(31) based;
i=5;
p=addr(i);
p->j=p->j+1;   /an other way to say i=i+1 */
put skip edit(i)(F(5));   /* ->  6 */

/* second form */
dcl i fixed bin(31);
dcl j fixed bin(31) based(p);
i=5;
p=addr(i);
j=j+1;   /* an other way to say i=i+1 */
put skip edit(i)(F(5));   /* ->  6 */

/* cascading pointers */
dcl (p,q,s,t) pointer;
dcl (j,k) fixed bin(31) based;
dcl (i1,i2) fixed bin(31);
p=addr(i1); t=addr(i2), q=addr(p); s=addr(t);
q->p->j = s->t->k + 3;   /* to say i1=i2+3 */


vars vec1, vec2;
;;; Create a vector and assign (reference to) it to vec1
consvector("a", "b", "c", 3) -> vec1;
;;; Copy (reference to) vector
vec1 -> vec2;
;;; Print value of vec1
vec1 =>
;;; Change first element of vec2
"d" -> vec2(1);
;;; Print value of vec1 -- the value changes because vec1 and
;;; vec2 reference the same vector
vec1 =>


Define varA.i = 5, varB.i = 0, *myInteger.Integer

*myInteger = @varA      ;set pointer to address of an integer variable
varB = *myInteger\i + 3 ;set variable to the 3 + value of dereferenced pointer, i.e varB = 8


 # Bind a literal string object to a name:
 a = "foo"
 # Bind an empty list to another name:
 b = []
 # Classes are "factories" for creating new objects: invoke class name as a function:
 class Foo(object):
     pass
 c = Foo()
 # Again, but with optional initialization:
 class Bar(object):
     def __init__(self, initializer = None)
         # "initializer is an arbitrary identifier, and "None" is an arbitrary default value
         if initializer is not None:
            self.value = initializer
 d = Bar(10)
 print d.value
 # Test if two names are references to the same object:
 if a is b: pass
 # Alternatively:
 if id(a) == id(b): pass
 # Re-bind a previous used name to a function:
 def a(fmt, *args):
     if fmt is None:
         fmt = "%s"
      print fmt % (args)
 # Append reference to a list:
 b.append(a)
 # Unbind a reference:
 del(a)
 # Call (anymous function object) from inside a list
 b[0]("foo")  # Note that the function object we original bound to the name "a" continues to exist
              # even if its name is unbound or rebound to some other object.


#lang racket

(define (inc! b) (set-box! b (add1 (unbox b))))

(define b (box 0))
(inc! b)
(inc! b)
(inc! b)
(unbox b) ; => 3


my $foo = 42;    # place a reference to 42 in $foo's item container
$foo++;          # deref $foo name, then increment the container's contents to 43
$foo.say;        # deref $foo name, then $foo's container, and call a method on 43.

$foo := 42;      # bind a direct ref to 42
$foo++;          # ERROR, cannot modify immutable value

my @bar = 1,2,3; # deref @bar name to array container, then set its values
@bar»++;         # deref @bar name to array container, then increment each value with a hyper
@bar.say;        # deref @bar name to array container, then call say on that, giving 2 3 4

@bar := (1,2,3); # bind name directly to a List
@bar»++;         # ERROR, parcels are not mutable


/* Using ADDR to get memory address, and PEEKC / POKE. There is also PEEK for numeric values. */
data _null_;
length a b c $4;
adr_a=addr(a);
adr_b=addr(b);
adr_c=addr(c);
a="ABCD";
b="EFGH";
c="IJKL";
b=peekc(adr_a,1);
call poke(b,adr_c,1);
put a b c;
run;


#!/usr/local/bin/shale

aVariable var                           // Create aVariable
aVariable 0 =                           // Regular assignment.
aVariable "aVariable = %d\n" printf     // Print aVariable

aPointer var                            // Create aPointer
aPointer aVariable &=                   // Pointer asssignment, aPointer now points to aVariable

aPointer-> "aPointer-> = %d\n" printf   // Pointer dereference. Print what aPointer points to

aPointer-> 3.141593 =                   // This will change the value of aVariable
aVariable "aVariable = %f\n" printf     // Print aVariable

aPPointer var                           // Create aPPointer
aPPointer aPointer &=                   // aPPointer is a pointer to a pointer
aPPointer->-> "aPPointer->-> = %f\n" printf

aPPointer->-> "abc123" =                // This will change the value of aVariable
aVariable "aVariable = %s\n" printf     // Print aVariable

// Shale pointers can point to any Shale object, like numbers, strings, variables
// and code fragments.


func assign2ref(ref, value) {
    *ref = value;
}

var x = 10;
assign2ref(\x, 20);
say x;      # x is now 20


val p = ref 1; (* create a new "reference" data structure with initial value 1 *)
val k = !p;    (* "dereference" the reference, returning the value inside *)
p := k + 1;    (* set the value inside to a new value *)


set var 3
set pointer var; # assign name "var" not value 3
set pointer;     # returns "var"
set $pointer;    # returns 3
set $pointer 42; # variable var now has value 42


Dim samplevariable as New Object
Dim anothervariable as Object
Set anothervariable = sameplevariable


// This function takes a string (behaves like a value type) and a list (reference type).
// The value and the reference are copied to their respective parameters.
var f = Fn.new { |s, l|
    if (s.type != String) Fiber.abort("First parameter must be a string.")
    if (l.type != List)   Fiber.abort("Second parameter must be a list.")
    // add the first argument to the list
    l.add(s) // the original 'l' will reflect this
    // mutate the first argument by reversing it
    s = s[-1..0] // the original 's' will not reflect this
}

var s = "wren"
var l = ["magpie", "finch"]
f.call(s, l)
System.print(l)
System.print(s)


\Paraphrasing the C example:
\This creates a pointer to an integer variable:
int Var, Ptr, V;
Ptr:= @Var;

\Access the integer variable through the pointer:
Var:= 3;
V:= Ptr(0);     \set V to the value of Var, i.e. 3
Ptr(0):= 42;    \set Var to 42

\Change the pointer to refer to another integer variable:
int OtherVar;
Ptr:= @OtherVar;

\Change the pointer to not point to anything:
Ptr:= 0;        \or any integer expression that evaluates to 0

\Set the pointer to the first item of an array:
int Array(10);
Ptr:= Array;
\Or alternatively:
Ptr:= @Array(0);

\Move the pointer to another item in the array:
def IntSize = 4;        \number of bytes in an integer
Ptr:= Ptr + 3*IntSize;  \pointer now points to Array(3)
Ptr:= Ptr - 2*IntSize;  \pointer now points to Array(1)

\Access an item in the array using the pointer:
V:= Ptr(3);     \get third item after Array(1), i.e. Array(4)
V:= Ptr(-1);    \get item immediately preceding Array(1), i.e. Array(0)
]


ld a,(&C000)  ;load the accumulator with the value from the memory address &C000.

ld hl,&D000
ld e,(hl)     ;load the E register with the byte at memory address &D000.

ld bc,(&E000) ;load the register pair BC from memory address &E000.
; This is the same as:
;  ld a,(&E000)
;  ld c,a
;  ld a,(&E001)
;  ld b,a

ld IX,&F000
ld a,(IX+3)   ;load A with the byte stored at &F003


package
{
    public class Point
    {
        protected var _x:Number;
        protected var _y:Number;

        public function Point(x:Number = 0, y:Number = 0)
        {
            _x = x;
            _y = y;
        }

        public function getX():Number
        {
            return _x;
        }

        public function setX(x:Number):void
        {
            _x = x;
        }

        public function getY():Number
        {
            return _y;
        }

        public function setY(y:Number):void
        {
            _x = y;
        }

        public function print():void
        {
            trace("Point");
        }
    }
}


package Shapes is
   type Point is tagged private;
   procedure Print(Item : in Point);
   function Setx(Item : in Point; Val : Integer) return Point;
   function Sety(Item : in Point; Val : Integer) return Point;
   function Getx(Item : in Point) return Integer;
   function Gety(Item : in Point) return Integer;
   function Create return Point;
   function Create(X : Integer) return Point;
   function Create(X, Y : Integer) return Point;

private
   type Point is tagged record
      X : Integer := 0;
      Y : Integer := 0;
   end record;
end Shapes;


class Point (protected x=0.0, protected y=0.0) {
    public function print {
        println ("Point")
    }

    public function getX { return x }
    public function getY { return y }

    public function setX(nx) { x = nx }
    public function setY(ny) { y = ny }
}

class Circle (x=0.0, y=0.0, r=0.0) extends Point (x, y) {
    public function print {
        println ("Circle")
    }

    public function getR { return r }
    public function setR(nr) { r = nr }
}

var p = new Point (1, 2)
var c = new Circle (1, 2, 3)
p.print()
c.print()


# Algol 68 provides for polymorphic operators but not procedures             #

# define the CIRCLE and POINT modes                                          #
MODE POINT  = STRUCT( REAL x, y    );
MODE CIRCLE = STRUCT( REAL x, y, r );

# PRINT operator                                                             #
OP PRINT = ( POINT  p )VOID: print( ( "Point(", x OF p, ",", y OF p, ")" ) );
OP PRINT = ( CIRCLE c )VOID: print( ( "Circle(", r OF c, " @ ", x OF c, ",", y OF c, ")" ) );

# getters                                                                    #
OP XCOORD = ( POINT p )REAL: x OF p;
OP YCOORD = ( POINT p )REAL: y OF p;

OP XCOORD = ( CIRCLE c )REAL: x OF c;
OP YCOORD = ( CIRCLE c )REAL: y OF c;
OP RADIUS = ( CIRCLE c )REAL: r OF c;

# setters                                                                    #
# the setters are dyadic operators so need a priority - we make them lowest  #
# priority, like PLUSAB etc.                                                 #
# They could have the same names as the getters but this seems clearer?      #
PRIO SETXCOORD = 1
   , SETYCOORD = 1
   , SETRADIUS = 1
   ;
# the setters return the POINT/CIRCLE being modified so we can write e.g.    #
# "PRINT ( p SETXCOORD 3 )"                                                  #
OP   SETXCOORD = ( REF POINT  p, REAL x )REF POINT:  ( x OF p := x; p );
OP   SETYCOORD = ( REF POINT  p, REAL y )REF POINT:  ( y OF p := y; p );

OP   SETXCOORD = ( REF CIRCLE c, REAL x )REF CIRCLE: ( x OF c := x; c );
OP   SETYCOORD = ( REF CIRCLE c, REAL y )REF CIRCLE: ( y OF c := y; c );
OP   SETRADIUS = ( REF CIRCLE c, REAL r )REF CIRCLE: ( r OF c := r; c );

# operands of an operator are not automatically coerced from INT to REAL so  #
# we also need these operators                                               #
OP   SETXCOORD = ( REF POINT  p, INT  x )REF POINT:  ( x OF p := x; p );
OP   SETYCOORD = ( REF POINT  p, INT  y )REF POINT:  ( y OF p := y; p );

OP   SETXCOORD = ( REF CIRCLE c, INT  x )REF CIRCLE: ( x OF c := x; c );
OP   SETYCOORD = ( REF CIRCLE c, INT  y )REF CIRCLE: ( y OF c := y; c );
OP   SETRADIUS = ( REF CIRCLE c, INT  r )REF CIRCLE: ( r OF c := r; c );

# copy constructors                                                          #
# A copy constructor is not needed as assignment will generate a copy        #
# e.g.: "POINT pa, pb; pa := ...; pb := pa; ..." will make pb a copy of pa   #

# assignment                                                                 #
# It is not possible to redefine the assignment "operator" in Algol 68 but   #
# assignment is automatically provided so no code need be written for e.g.   #
# "CIRCLE c1 := ...."                                                        #

# destructors                                                                #
# Algol 68 does not include destructors. A particular postlude could,        #
# in theory be provided if specific cleanup was requried, but this would     #
# occur at the end of the program, not at the end of the lifetime of the     #
# object.                                                                    #

# default constructor                                                        #
# Algol 68 automatically provides generators HEAP and LOC, which will        #
# create new objects of the specified MODE, e.g. HEAP CIRCLE will create a   #
# new CIRCLE. HEAP allocates apace on the heap, LOC allocates in on the      #
# stack (so the new item disappears when the enclosing block procedure or    #
# operator finishes)                                                         #

# a suitable "display" (value list enclosed in "(" and ")") can be cast to   #
# the relevent MODE, allowing us to write e.g.:                              #
# "POINT( 3.1, 2.2 )" where we need a new item.                              #

# "constructors" with other than all the fields in the correct order could   #
# be provided as procedures but each would need a distinct name              #
# e.g.                                                                       #
PROC new circle at the origin = ( REAL r )REF CIRCLE:
      ( ( HEAP CIRCLE SETRADIUS r ) SETXCOORD 0 ) SETYCOORD 0;
PROC new point at the origin = REF POINT:
      ( HEAP POINT SETXCOORD 0 ) SETYCOORD 0;

# examples of use                                                            #

BEGIN

    CIRCLE c1 := CIRCLE( 1.1, 2.4, 4.1 );
    POINT  p1 := new point at the origin;

    PRINT c1; newline( stand out );

    # move c1 so it is centred on p1                                         #
    ( c1 SETXCOORD XCOORD p1 ) SETYCOORD YCOORD p1;

    PRINT c1; newline( stand out )

END


define :point [x,y][
    init: [
        ensure -> is? :floating this\x
        ensure -> is? :floating this\y
    ]

    print: [
        render "point (x: |this\x|, y: |this\y|)"
    ]
]

define :circle [center,radius][
    init: [
        ensure -> is? :point this\center
        ensure -> is? :floating this\radius
    ]

    print: [
        render "circle (center: |this\center|, radius: |this\radius|)"
    ]
]

p: to :point [10.0, 20.0]
c: to :circle @[p, 10.0]

inspect p
inspect c

print p
print c


MyPoint := new Point(1, 8)
MyPoint.Print()
MyCircle := new Circle(4, 7, 9)
MyCircle2 := MyCircle.Copy()
MyCircle.SetX(2)	;Assignment method
MyCircle.y := 3		;Direct assignment
MyCircle.Print()
MyCircle2.Print()
MyCircle.SetX(100), MyCircle.SetY(1000), MyCircle.r := 10000
MsgBox, % MyCircle.__Class
	. "`n`nx:`t" MyCircle.GetX()
	. "`ny:`t" MyCircle.y
	. "`nr:`t" MyCircle.GetR()
return

class Point
{
	Copy()
	{
		return this.Clone()
	}
	GetX()
	{
		return this.x
	}
	GetY()
	{
		return this.y
	}
	__New(x, y)
	{
		this.x := x
		this.y := y
	}
	Print()
	{
		MsgBox, % this.__Class
			. "`n`nx:`t" this.x
			. "`ny:`t" this.y
	}
	SetX(aValue)
	{
		this.x := aValue
	}
	SetY(aValue)
	{
		this.y := aValue
	}
}

class Circle extends Point
{
	GetR()
	{
		return this.r
	}
	__New(x, y, r)
	{
		this.r := r
		base.__New(x, y)
	}
	Print()
	{
		MsgBox, % this.__Class
			. "`n`nx:`t" this.x
			. "`ny:`t" this.y
			. "`nr:`t" this.r
	}
	SetR(aValue)
	{
		this.r := aValue
	}
}


      INSTALL @lib$ + "CLASSLIB"

      REM Create parent class with void 'doprint' method:
      DIM PrintableShape{doprint}
      PROC_class(PrintableShape{})

      REM Create derived class for Point:
      DIM Point{x#, y#, setxy, retx, rety, @constructor, @@destructor}
      PROC_inherit(Point{}, PrintableShape{})
      DEF Point.setxy (x,y) : Point.x# = x : Point.y# = y : ENDPROC
      DEF Point.retx = Point.x#
      DEF Point.rety = Point.y#
      DEF [email protected] Point.x# = 1.23 : Point.y# = 4.56 : ENDPROC
      DEF [email protected]@destructor : ENDPROC
      DEF Point.doprint : PRINT Point.x#, Point.y# : ENDPROC
      PROC_class(Point{})

      REM Create derived class for Circle:
      DIM Circle{x#, y#, r#, setxy, setr, retx, rety, retr, @con, @@des}
      PROC_inherit(Circle{}, PrintableShape{})
      DEF Circle.setxy (x,y) : Circle.x# = x : Circle.y# = y : ENDPROC
      DEF Circle.setr (r) : Circle.r# = r : ENDPROC
      DEF Circle.retx = Circle.x#
      DEF Circle.rety = Circle.y#
      DEF Circle.retr = Circle.r#
      DEF [email protected] Circle.x# = 3.2 : Circle.y# = 6.5 : Circle.r# = 7 : ENDPROC
      DEF [email protected]@des : ENDPROC
      DEF Circle.doprint : PRINT Circle.x#, Circle.y#, Circle.r# : ENDPROC
      PROC_class(Circle{})

      REM Test the polymorphic 'doprint' function:
      PROC_new(mypoint{}, Point{})
      PROC(mypoint.doprint)
      PROC_discard(mypoint{})
      PROC_new(mycircle{}, Circle{})
      PROC(mycircle.doprint)
      PROC_discard(mycircle{})
      END


using System;
class Point
{
  protected int x, y;
  public Point() : this(0) {}
  public Point(int x) : this(x,0) {}
  public Point(int x, int y) { this.x = x; this.y = y; }
  public int X { get { return x; } set { x = value; } }
  public int Y { get { return y; } set { y = value; } }
  public virtual void print() { System.Console.WriteLine("Point"); }
}

public class Circle : Point
{
  private int r;
  public Circle(Point p) : this(p,0) { }
  public Circle(Point p, int r) : base(p) { this.r = r; }
  public Circle() : this(0) { }
  public Circle(int x) : this(x,0) { }
  public Circle(int x, int y) : this(x,y,0) { }
  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }
  public int R { get { return r; } set { r = value; } }
  public override void print() { System.Console.WriteLine("Circle"); }

  public static void main(String args[])
  {
    Point p = new Point();
    Point c = new Circle();
    p.print();
    c.print();
  }
}


#include <cstdio>
#include <cstdlib>

class Point {
protected:
    int x, y;

public:
    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}
    Point(const Point &p) : x(p.x), y(p.y) {}
    virtual ~Point() {}
    const Point& operator=(const Point &p) {
        if (this != &p) {
            x = p.x;
            y = p.y;
        }
        return *this;
    }
    int getX() { return x; }
    int getY() { return y; }
    void setX(int x0) { x = x0; }
    void setY(int y0) { y = y0; }
    virtual void print() { printf("Point\n"); }
};

class Circle: public Point {
private:
    int r;

public:
    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}
    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}
    virtual ~Circle() {}
    const Circle& operator=(const Circle &c) {
        if (this != &c) {
            x = c.x;
            y = c.y;
            r = c.r;
        }
        return *this;
    }
    int getR() { return r; }
    void setR(int r0) { r = r0; }
    virtual void print() { printf("Circle\n"); }
};

int main() {
    Point *p = new Point();
    Point *c = new Circle();
    p->print();
    c->print();
    delete p;
    delete c;

    return EXIT_SUCCESS;
}


import ceylon.language {
    consolePrint = print
}

shared void run() {

    class Point {

        shared variable Integer x;
        shared variable Integer y;

        shared new(Integer x = 0, Integer y = 0) {
            this.x = x;
            this.y = y;
        }

        shared new copy(Point p) {
            this.x = p.x;
            this.y = p.y;
        }

        shared default void print() {
            consolePrint("[Point ``x`` ``y``]");
        }
    }

    class Circle extends Point {

        shared variable Integer r;

        shared new(Integer x = 0, Integer y = 0, Integer r = 0) extends Point(x, y) {
            this.r = r;
        }

        shared new copy(Circle c) extends Point.copy(c){
            this.r = c.r;
        }

        shared actual void print() {
            consolePrint("[Circle ``x`` ``y`` ``r``]");
        }
    }

    value shapes = [
        Point(), Point(1), Point(1, 2), Point {y = 3;}, Point.copy(Point(4, 5)),
        Circle(), Circle(1), Circle(2, 3), Circle(4, 5, 6), Circle {y = 7; r = 8;}, Circle.copy(Circle(9, 10, 11))
    ];

    for(shape in shapes) {
        shape.print();
    }
}


(defprotocol Printable
  (print-it [this] "Prints out the Printable."))

(deftype Point [x y]
  Printable
  (print-it [this] (println (str "Point: " x " " y))))

(defn create-point
  "Redundant constructor function."
  [x y] (Point. x y))

(deftype Circle [x y r]
  Printable
  (print-it [this] (println (str "Circle: " x " " y " " r))))

(defn create-circle
  "Redundant consturctor function."
  [x y r] (Circle. x y r))


(defclass point ()
  ((x :initarg :x :initform 0 :accessor x)
   (y :initarg :y :initform 0 :accessor y)))

(defclass circle (point)
  ((radius :initarg :radius :initform 0 :accessor radius)))

(defgeneric shallow-copy (object))
(defmethod shallow-copy ((p point))
  (make-instance 'point :x (x p) :y (y p)))
(defmethod shallow-copy ((c circle))
  (make-instance 'circle :x (x c) :y (y c) :radius (radius c)))

(defgeneric print-shape (shape))
(defmethod print-shape ((p point))
  (print 'point))
(defmethod print-shape ((c circle))
  (print 'circle))

(let ((p (make-instance 'point :x 10))
      (c (make-instance 'circle :radius 5)))
  (print-shape p)
  (print-shape c))


import std.stdio: writeln;

class Point {
    private int x, y;
    this(int x_=0, int y_=0) { x = x_; y = y_; }
    this(Point p_) { x = p_.getX(); y = p_.getY(); }
    int getX() { return x; }
    void setX(int x_) { this.x = x_; }
    int getY() { return y; }
    void setY(int y_) { this.y = y_; }
}

class Circle : Point {
    private int r;
    this(int x_=0, int y_=0, int r_=0) {
        super(x_, y_);
        r = r_;
    }
    this(Point p, int r_=0) {
        super(p);
        r = r_;
    }
    this(Circle c_) {
        super(c_.getX(), c_.getY());
        r = c_.getR();
    }
    int getR() { return r; }
    void setR(int r0) { this.r = r0; }
}

void main() {
    auto p = new Point();
    auto c = new Circle();
    writeln(p);
    writeln(c);
}


type
  { TPoint }

  TMyPoint = class
  private
    FX: Integer;
    FY: Integer;
  public
    constructor Create; overload;
    constructor Create(X0: Integer; Y0: Integer); overload;
    constructor Create(MyPoint: TMyPoint); overload;
    destructor Destroy; override;

    procedure Print; virtual;

    property X: Integer read FX write FX;
    property Y: Integer read FY write FY;
  end;

  { TCircle }

  TCircle = class(TMyPoint)
  private
    FR: Integer;
  public
    constructor Create(X0: Integer; Y0: Integer; R0: Integer); overload;
    constructor Create(MyPoint: TMyPoint; R0: Integer); overload;
    constructor Create(Circle: TCircle); overload;
    destructor Destroy; override;

    procedure Print; override;

    property R: Integer read FR write FR;
  end;

implementation

uses Dialogs;

{ TCircle }

constructor TCircle.Create(X0: Integer; Y0: Integer; R0: Integer);
begin
  inherited Create(X0, Y0);
  FR := R0;
end;

constructor TCircle.Create(MyPoint: TMyPoint; R0: Integer);
begin
  inherited Create(MyPoint);
  FR := R0;
end;

constructor TCircle.Create(Circle: TCircle);
begin
  Create;
  if not(Circle = Self) then
  begin
    FX := Circle.X;
    FY := Circle.Y;
    FR := Circle.R;
  end;
end;

destructor TCircle.Destroy;
begin
  inherited Destroy;
end;

procedure TCircle.Print;
begin
   ShowMessage('Circle');
end;

{ TMyPoint }

constructor TMyPoint.Create;
begin
  inherited Create;
end;

constructor TMyPoint.Create(X0: Integer; Y0: Integer);
begin
  Create;
  FX := X0;
  FY := Y0;
end;

constructor TMyPoint.Create(MyPoint: TMyPoint);
begin
  Create;
  if not(MyPoint = Self) then
  begin
    FX := MyPoint.X;
    FY := MyPoint.Y;
  end;
end;

destructor TMyPoint.Destroy;
begin
  inherited Destroy;
end;

procedure TMyPoint.Print;
begin
  ShowMessage('MyPoint');
end;


def makePoint(x, y) {
  def point implements pbc {
    to __printOn(out) { out.print(`<point $x,$y>`) }
    to __optUncall() { return [makePoint, "run", [x, y]] }
    to x() { return x }
    to y() { return y }
    to withX(new) { return makePoint(new, y) }
    to withY(new) { return makePoint(x, new) }
  }
  return point
}

def makeCircle(x, y, r) {
  def circle extends makePoint(x, y) implements pbc {
    to __printOn(out) { out.print(`<circle $x,$y r $r>`) }
    to __optUncall() { return [makeCircle, "run", [x, y, r]] }
    to r() { return r }
    to withX(new) { return makeCircle(new, y, r) }
    to withY(new) { return makeCircle(x, new, r) }
    to withR(new) { return makeCircle(x, y, new) }
  }
  return circle
}


(struct Point ((real:x 0) (real:y 0)))
(struct Circle ((real:x 0) (real:y 0) (real:r 1)))

(define-method (print Point:p) (printf "📌 [%d %d]" p.x p.y))
(define-method (print Circle:c) (printf "⭕ center:[%d %d] radius:%d" c.x c.y c.r))

(print (Point 5 6))
    → 📌 [5 6]
(print (Circle 2 3 4))
    → ⭕ center:[2 3] radius:4

;; Accessors :
;; (Point-x p), (Point-y p) or p.x, p.y
;; (Circle-x c), c.x , etc.
;; Setters :
;; (set-Point-x! p value), (set-Circle-r!  c value)  etc.

;; Constructors
;; (Point) (Point x) (Point x y)
;; (Circle) (circle x) (Circle x y) (Circle x y r)

;;Copy
(print (copy (Circle 3 3 )))
    →  ⭕ center:[3 3] radius:1

;;Assignment (to a variable)
(define my-point (Point 7 8))

;;Destructor : none. Points and Circles are garbage collected.

;;Type checking
(Point "here" "there")
    💣 error: Real : type-check failure : here → 'Point:x'

;;Initializer procedure
(struct Circle ((x 0) (y 0) (r 1) d) #:initialize circle-init)
(define (circle-init Circle:c) (set-Circle-d! c (* 2 PI c.r)))
(define-method (print Circle:c)
    (printf "⭕ center:[%d %d] radius:%d diameter:%d" c.x c.y c.r c.d))

(print (Circle 0 0 10))
    → ⭕ center:[0 0] radius:10 diameter:62.83185307179586


class
    POINT
inherit
    ANY
        redefine
            out
        end
create
    make, make_origin

feature -- Initialization

    make (a_x, a_y: INTEGER)
            -- Create with values `a_x' and `a_y'
        do
            set_x (a_x)
            set_y (a_y)
        ensure
            x_set: x = a_x
            y_set: y = a_y
        end

    make_origin
            -- Create at origin
        do
        ensure
            x_set: x = 0
            y_set: y = 0
        end

feature -- Access

    x: INTEGER assign set_x
            -- Horizontal axis coordinate

    y: INTEGER assign set_y
            -- Vertical axis coordinate

feature -- Element change

    set_x (a_x: INTEGER)
            -- Set `x' coordinate to `a_x'
        do
            x := a_x
        ensure
            x_set: x = a_x
        end

    set_y (a_y: INTEGER)
            -- Set `y' coordinate to `a_y'
        do
            y := a_y
        ensure
            y_set: y = a_y
        end

feature -- Output

    out: STRING
            -- Display as string
        do
            Result := "Point:   x = " + x.out + "   y = " + y.out
        end
end


type Point = Point x y

instance Show Point where
  show (Point x y) = "Point " ++ (show x) ++ " " ++ (show y)

instance Name Point where
  getField nm (Point x y)
    | nm == "x" = x
    | nm == "y" = y
    | else = fail "Undefined name."
  isField nm _ = nm == "x" || nm == "y"

pointX = flip Point 0

pointY = Point 0

pointEmpty = Point 0 0

type Circle = Circle x y z

instance Show Circle where
  show (Circle x y z) =
    "Circle " ++ (show x) ++ " " ++ (show y) ++ " " ++ (show z)

instance Name Circle where
  getField nm (Circle x y z)
    | nm == "x" = x
    | nm == "y" = y
    | nm == "z" = z
    | else = fail "Undefined name."
  isField nm _ = nm == "x" || nm == "y" || nm == "z"

circleXZ = flip Circle 0

circleX x = Circle x 0 0

circleYZ = Circle 0

circleY y = Circle 0 y 0

circleZ = Circle 0 0

circleEmpty = Circle 0 0 0


import extensions;

class Point
{
    prop int X;
    prop int Y;

    constructor new(int x, int y)
    {
        X := x;
        Y := y
    }

    constructor new()
        <= new(0,0);

    print() { console.printLine("Point") }
}

class Circle : Point
{
    prop int R;

    constructor new()
        <= new(0);

    constructor new(int r)
        <= new(0, 0, r);

    constructor new(int x, int y, int r)
        <= new(x, y)
    {
        R := r
    }

    print() { console.printLine("Circle") }
}

public program()
{
    Point p := Point.new();
    Point c := Circle.new();

    p.print();
    c.print()
}


type Printable =
  abstract member Print : unit -> unit

type Point(?x, ?y) =
  member t.x = defaultArg x 0.0
  member t.y = defaultArg y 0.0
  interface Printable with
     member t.Print() = printfn "Point(x:%f, y:%f)" t.x t.y

type Circle(?center, ?radius) =
  member t.center = defaultArg center (new Point())
  member t.radius = defaultArg radius 1.0
  interface Printable with
    member t.Print() =
      printfn "Circle(x:%f, y:%f, r:%f)" t.center.x t.center.y t.radius


QUALIFIED: io  ! there already is print in io

GENERIC: print ( shape -- )

TUPLE: point x y ;
C: <point> point  ! shorthand constructor definition

M: point print drop "Point" io:print ;

TUPLE: circle radius x y ;
C: <circle> circle

M: circle print drop "Circle" io:print ;


include lib/memcell.4th
include 4pp/lib/foos.4pp

:: Point                               ( xn n a--)
   class
     field:  x                         \ x coordinate
     field:  y                         \ y coordinate
     method: print                     \ print routine
     method: setx                      \ set x coordinate
     method: sety                      \ set y coordinate
     method: getx                      \ get x coordinate
     method: gety                      \ get y coordinate
   end-class {
                                       \ bind the methods immediately
     :method { this -> x ! } ; defines setx
     :method { this -> y ! } ; defines sety
     :method { this -> x @ } ; defines getx
     :method { this -> y @ } ; defines gety
                                       \ because we'll use them immediately
     :method {                         \ e.g. in this print routine
       ." Point(" this => getx 0 .r ." ," this => gety 0 .r ." )" cr
     } ; defines print                 \ and this initialization
                                       \ object or argument count
     dup [email protected] this [email protected] =            \ if it is an object, a point
     if                                \ get the coordinates and set them
       dup => getx this => setx
           => gety this => sety
     else                              \ otherwise initialize it
       0 dup this => setx this => sety
       case                            \ and check the argument count
         1 of this => setx endof       \ one argument : x only
         2 of this => setx             \ two arguments: x and y
              this => sety endof
       endcase
     then

     private{ x y }                    \ make x and y private
   }
;

:: Circle                              ( xn n a --)
   over >r                             ( arg-count object-addr)
   extends Point                       \ save the argument count!!
     field:  r                         \ radius
     method: getr                      \ get radius
     method: setr                      \ set radius
   end-extends r> swap {               \ retrieve count
                                       \ bind the methods immediately
     :method { this -> r ! } ; defines setr
     :method { this -> r @ } ; defines getr
                                       \ because we'll use them immediately
     :method {                         \ e.g. in this print routine
       ." Circle(" this => getx 0 .r ." ,"
                   this => gety 0 .r ." ,"
                   this => getr 0 .r ." )" cr
     } ; defines print                 \ and this initialization
                                       \ object or argument count
     dup [email protected] this [email protected] =            \ if it is an object, a circle
     if                                \ get the coordinates and set them
       dup => getx this => setx
       dup => gety this => sety
           => getr this => setr
     else                              \ otherwise initialize it
       0 this => setr
       case                            \ and check the argument count
         3 of this => setr             \ three arguments: x, y and r
              this => sety             \ note the rest is already set
              this => setx endof       \ by "Point" and r was left on
       endcase                         \ the stack!
     then

     private{ r }
   }
;

0 new Point Point1
Point1 => print
45 23 2 new Point Point2
Point2 => print
Point2 new Point Point3
Point3 => print
78 1 new Point Point4
Point4 => print
10 45 23 3 new Circle Circle1
Circle1 => print
Point2 new Circle Circle2
Circle2 => print
Circle1 new Circle Circle3
Circle3 => print


module geom

  type point
     real(8), private  :: x = 0
     real(8), private  :: y = 0
   contains
     procedure, public :: get_x
     procedure, public :: get_y
     procedure, public :: set_x
     procedure, public :: set_y
     procedure, public :: print => print_point
     procedure, pass :: copy_point
     !overloaded assignment operator
     generic, public :: assignment(=) => copy_point
  end type point

  type, extends(point) :: circle
     real(8), private  :: r = 0
   contains
     procedure, public :: get_r
     procedure, public :: set_r
     procedure, public :: print => print_circle
     procedure, pass :: copy_circle
     !overloaded assignment operator
     generic, public :: assignment(=) => copy_circle
  end type circle

  ! constructor interface
  interface circle
  module procedure circle_constructor
  end interface circle
  ! constructor interface
  interface point
  module procedure point_constructor
  end interface point

contains

  real(8) function get_x(this)
    class(point), intent(in) :: this
    get_x = this%x
  end function get_x

  real(8) function get_y(this)
    class(point), intent(in) :: this
    get_y = this%y
  end function get_y

  subroutine set_x(this, val)
    class(point), intent(inout) :: this
    real(8), intent(in)         :: val
    this%x = val
  end subroutine set_x

  subroutine set_y(this, val)
    class(point), intent(inout) :: this
    real(8), intent(in)         :: val
    this%y = val
  end subroutine set_y

  subroutine print_point(this)
    class(point), intent(in) :: this
    write(*,'(2(a,f0.4),a)') 'Point(',this%x,', ',this%y,')'
  end subroutine print_point

  real(8) function get_r(this)
    class(circle), intent(in) :: this
    get_r = this%r
  end function get_r

  subroutine set_r(this, val)
    class(circle), intent(inout) :: this
    real(8), intent(in)          :: val
    this%r = val
  end subroutine set_r

  subroutine print_circle(this)
    class(circle), intent(in) :: this
    write(*,'(3(a,f0.4),a)') 'Circle(',this%x,', ',this%y,'; ',this%r,')'
  end subroutine print_circle

  subroutine copy_point(this, rhs)
      class(point), intent(inout) :: this
      type(point), intent(in) :: rhs
      this%x = rhs%x
      this%y = rhs%y
  end subroutine copy_point

  subroutine copy_circle(this, rhs)
      class(circle), intent(inout) :: this
      type(circle), intent(in) :: rhs
      this%x = rhs%x
      this%y = rhs%y
      this%r = rhs%r
  end subroutine copy_circle

! non-default constructor to init private components
  type(point) function point_constructor(x,y)
  real(8), intent(in) :: x,y
  point_constructor%x = x
  point_constructor%y = y
  end function point_constructor
! non-default constructor to init private components
  type(circle) function circle_constructor(x,y,r)
  real(8), intent(in) :: x,y,r
  circle_constructor%x = x
  circle_constructor%y = y
  circle_constructor%r = r
  end function circle_constructor

end module geom

program inh
  use geom

  type(point)  :: p, p_copy
  type(circle) :: c, c_copy

  p = point(2.0d0, 3.0d0)
  call p%print
  p_copy = p
  call p_copy%print

  c = circle(3.0d0, 4.0d0, 5.0d0)
  call c%print
  c_copy = c
  call c_copy%print

end program inh


package main

import "fmt"

type point struct {
    x, y float64
}

type circle struct {
    x, y, r float64
}

type printer interface {
    print()
}

func (p *point) print() {
    fmt.Println(p.x, p.y)
}

func (c *circle) print() {
    fmt.Println(c.x, c.y, c.r)
}

func main() {
    var i printer            // polymorphic variable
    i = newPoint(3, 4)       // assign one type
    i.print()                // call polymorphic function
    i = newCircle(5, 12, 13) // assign different type to same variable
    i.print()                // same call accesses different method now.
}

// Above is a sort of polymorphism: both types implement the printer
// interface.  The print function can be called through a variable
// of type printer, without knowing the underlying type.

// Below is other stuff the task asks for.  Note that none of it is
// needed for cases as simple as this task, and it is not idomatic
// to write any of these functions in these simple cases.

// Accessors are not idiomatic in Go.  Instead, simply access struct
// fields directly.  To allow access from another package, you "export"
// the field by capitalizing the field name.
func (p *point) getX() float64  { return p.x }
func (p *point) getY() float64  { return p.y }
func (p *point) setX(v float64) { p.x = v }
func (p *point) setY(v float64) { p.y = v }

func (c *circle) getX() float64  { return c.x }
func (c *circle) getY() float64  { return c.y }
func (c *circle) getR() float64  { return c.r }
func (c *circle) setX(v float64) { c.x = v }
func (c *circle) setY(v float64) { c.y = v }
func (c *circle) setR(v float64) { c.r = v }

// Copy constructors, not idiomatic.  Structs are assignable so
// you can simply declare and assign them as needed.
func (p *point) clone() *point   { r := *p; return &r }
func (c *circle) clone() *circle { r := *c; return &r }

// Assignment methods, not idiomatic.  Just use the assignment operator.
func (p *point) set(q *point)   { *p = *q }
func (c *circle) set(d *circle) { *c = *d }

// Constructors are idiomatic only when construction involves something
// more than just assigning initial values.  By default, structs
// are created as "zero values," that is, with all fields zero,
// empty, or nil.  The struct literal synax allows for all fields to
// initialized, or for any subset of fields to be initialized by name.
// These feautures take the place of trivial default constructors.
// When additional initialization is needed, it is conventional to
// name a function New, New<Type>, or within a package, new<Type>
// as shown here.
func newPoint(x, y float64) *point {
    return &point{x, y}
}
func newCircle(x, y, r float64) *circle {
    return &circle{x, y, r}
}

// Destructors are never used in Go.  Objects are garbage collected.


#!/usr/bin/env golosh
----
This module demonstrates Golo's version of polymorphism.
----
module Polymorphism

# Each struct automatically gets a constructor and also accessor and assignment methods for each field.
# For example, the constructor for Point is Point(1, 2)
# and the accessor methods are x() and y()
# and the assignment methods are x(10) and y(10).

struct Point = { x, y }
struct Circle = { x, y, r }

# Augmentations are the way to give your struct methods.
# They're like extension methods in C# or Xtend.

augment Point {

  function print = |this| { println("Point " + this: x() + " " + this: y()) }
}

augment Circle {

  function print = |this| { println("Circle " + this: x() + " " + this: y() + " " + this: r()) }
}

# You can define functions with the same name as your struct that work
# basically like constructors.

----
A contructor with no arguments that initializes all fields to 0
----
function Point = -> Point(0, 0)

----
This is the copy constructor when the argument is another point
----
function Point = |x| -> match {
  when x oftype Point.class then Point(x: x(), x: y())
  otherwise Point(x, 0)
}

----
A contructor with no arguments that initializes all fields to 0
----
function Circle = -> Circle(0, 0, 0)

----
This is the copy constructor when the argument is another circle
----
function Circle = |x| -> match {
  when x oftype Circle.class then Circle(x: x(), x: y(), x: r())
  otherwise Circle(x, 0, 0)
}

----
This one initializes the radius to zero
----
function Circle = |x, y| -> Circle(x, y, 0)

function main = |args| {
  let p = Point(10, 20)
  let c = Circle(10, 20, 30)
  let shapes = vector[
    Point(), Point(1), Point(1, 2), Point(p),
    Circle(), Circle(1), Circle(1, 2), Circle(1, 2, 3), Circle(c)
  ]
  foreach shape in shapes {
    shape: print()
  }
}


@Canonical
@TupleConstructor(force = true)
@ToString(includeNames = true)
class Point {
    Point(Point p) { x = p.x; y = p.y }
    void print() { println toString() }
    Number x
    Number y
}

@Canonical
@TupleConstructor(force = true)
@ToString(includeNames = true, includeSuper = true)
class Circle extends Point {
    Circle(Circle c) { super(c); r = c.r }
    void print() { println toString() }
    Number r
}


data Point = Point Integer Integer
instance Show Point where
    show (Point x y) = "Point at "++(show x)++","++(show y)

-- Constructor that sets y to 0
ponXAxis = flip Point 0

-- Constructor that sets x to 0
ponYAxis = Point 0

-- Constructor that sets x and y to 0
porigin = Point 0 0

data Circle = Circle Integer Integer Integer
instance Show Circle where
    show (Circle x y r) = "Circle at "++(show x)++","++(show y)++" with radius "++(show r)

-- Constructor that sets y to 0
conXAxis = flip Circle 0

-- Constructor that sets x to 0
conYAxis = Circle 0

-- Constructor that sets x and y to 0
catOrigin = Circle 0 0

--Constructor that sets y and r to 0
c0OnXAxis = flip (flip Circle 0) 0

--Constructor that sets x and r to 0
c0OnYAxis = flip (Circle 0) 0


class Circle (x, y, r)
  # make a new copy of this instance
  method copy ()
    return Circle (x, y, r)
  end

  # print a representation of this instance
  method print ()
    write ("Circle (" || x || ", " || y || ", " || r || ")")
  end

  # called during instance construction, to pass in field values
  initially (x, y, r)
    self.x := if /x then 0 else x # set to 0 if argument not present
    self.y := if /y then 0 else y
    self.r := if /r then 0 else r

end

class Point (x, y)
  # make a new copy of this instance
  method copy ()
    return Point (x, y)
  end

  # print a representation of this instance
  method print ()
    write ("Point (" || x || ", " || y || ")")
  end

  # called during instance construction, to pass in field values
  initially (x, y)
    self.x := if /x then 0 else x # set to 0 if argument not present
    self.y := if /y then 0 else y

end

procedure main ()
  p1 := Point ()
  p2 := Point (1)
  p3 := Point (1,2)
  p4 := p3.copy ()

  write ("Points:")
  p1.print ()
  p2.print ()
  p3.print ()
  p4.print ()
  # demonstrate field mutator/accessor
  p3.x := 3
  write ("p3 value of x is: " || p3.x)

  c1 := Circle ()
  c2 := Circle (1)
  c3 := Circle (1,2)
  c4 := Circle (1,2,3)

  write ("Circles:")
  c1.print ()
  c2.print ()
  c3.print ()
  c4.print ()
end


Space is a room.

A point is a kind of thing.
A point has a number called X position.
A point has a number called Y position.

A circle is a kind of point.
A circle has a number called radius.

To print (P - point): say "Point: [X position of P], [Y position of P]."
To print (C - circle): say "Circle: [X position of C], [Y position of C] radius [radius of C]."

The origin is a point with X position 0 and Y position 0.
The circle of power is a circle with X position 100, Y position 25, radius 7.

When play begins:
	print the origin;
	print the circle of power;
	end the story.


coclass 'Point'
create=: monad define
  'X Y'=:2{.y
)
getX=: monad def 'X'
getY=: monad def 'Y'
setX=: monad def 'X=:y'
setY=: monad def 'Y=:y'
print=: monad define
  smoutput 'Point ',":X,Y
)
destroy=: codestroy


class Point {
   protected int x, y;
   public Point() { this(0); }
   public Point(int x) { this(x, 0); }
   public Point(int x, int y) { this.x = x; this.y = y; }
   public Point(Point p) { this(p.x, p.y); }
   public int getX() { return this.x; }
   public int getY() { return this.y; }
   public void setX(int x) { this.x = x; }
   public void setY(int y) { this.y = y; }
   public void print() { System.out.println("Point x: " + this.x + " y: " + this.y); }
}

class Circle extends Point {
   private int r;
   public Circle(Point p) { this(p, 0); }
   public Circle(Point p, int r) { super(p); this.r = r; }
   public Circle() { this(0); }
   public Circle(int x) { this(x, 0); }
   public Circle(int x, int y) { this(x, y, 0); }
   public Circle(int x, int y, int r) { super(x, y); this.r = r; }
   public Circle(Circle c) { this(c.x, c.y, c.r); }
   public int getR() { return this.r; }
   public void setR(int r) { this.r = r; }
   public void print() { System.out.println("Circle x: " + this.x + " y: " + this.y + " r: " + this.r); }
}

public class test {
  public static void main(String args[]) {
    Point p = new Point();
    Point c = new Circle();
    p.print();
    c.print();
  }
}


/* create new Point in one of these ways:
 *    var p = new Point(x,y);
 *    var p = new Point(a_point);
 * default value for x,y is 0
 */
function Point() {
    var arg1 = arguments[0];
    var arg2 = arguments[1];

    if (arg1 instanceof Point) {
        this.x = arg1.x;
        this.y = arg1.y;
    }
    else {
        this.x = arg1 == null ? 0 : arg1;
        this.y = arg2 == null ? 0 : arg1;
    }

    this.set_x = function(_x) {this.x = _x;}
    this.set_y = function(_y) {this.y = _y;}
}

Point.prototype.print = function() {
    var out = "Point(" + this.x + "," + this.y + ")";
    print(out);
}

/* create new Circle in one of these ways:
 *    var c = new Circle(x,y,r);
 *    var c = new Circle(a_circle);
 *    var c = new Circle(a_point,r);
 * default value for x,y,r is 0
 */
function Circle() {
    var arg1 = arguments[0];
    var arg2 = arguments[1];
    var arg3 = arguments[2];

    if (arg1 instanceof Circle) {
        this.x = arg1.x;
        this.y = arg1.y;
        this.r = arg1.r;
    }
    else if (arg1 instanceof Point) {
        this.x = arg1.x;
        this.y = arg1.y;
        this.r = arg2 == null ? 0 : arg2;
    }
    else {
        this.x = arg1 == null ? 0 : arg1;
        this.y = arg2 == null ? 0 : arg2;
        this.r = arg3 == null ? 0 : arg3;
    }

    this.set_x = function(_x) {this.x = _x;}
    this.set_y = function(_y) {this.y = _y;}
    this.set_r = function(_r) {this.r = _r;}
}

Circle.prototype.print = function() {
    var out = "Circle(" + this.x + "," + this.y + "," + this.r + ")";
    print(out);
}


def Point(x;y): {"type": "Point", "x": x, "y": y};
def Point(x): Point(x;0);
def Point: Point(0);

def Circle(x;y;r): {"type": "Circle", "x": x, "y": y, "r": r};
def Circle(x;y): Circle(x;y;0);
def Circle(x): Circle(x;0);
def Circle: Circle(0);

def print:
  if  .type == "Circle" then "\(.type)(\(.x); \(.y); \(.r))"
  elif .type == "Point" then "\(.type)(\(.x); \(.y))"
  else empty
  end;


mutable struct Point
	x::Float64
	y::Float64
end

Base.show(io::IO, p::Point) = print(io, "Point($(p.x), $(p.y))")

getx(p::Point) = p.x
gety(p::Point) = p.y

setx(p::Point, x) = (p.x = x)
sety(p::Point, y) = (p.y = y)

mutable struct Circle
	x::Float64
	y::Float64
	r::Float64
end

getx(c::Circle) = c.x
gety(c::Circle) = c.y
getr(c::Circle) = c.r

setx(c::Circle, x) = (c.x = x)
sety(c::Circle, y) = (c.y = y)
setr(c::Circle, r) = (c.r = r)

Base.show(io::IO, c::Circle) = print(io, "Circle($(c.x), $(c.y), $(c.r))")


// version 1.1.2

open class Point(var x: Int, var y: Int) {
    constructor(): this(0, 0)

    constructor(x: Int) : this(x, 0)

    constructor(p: Point) : this(p.x, p.y)

    open protected fun finalize() = println("Finalizing $this...")

    override fun toString() = "Point at ($x, $y)"

    open fun print() = println(this)
}

class Circle(x: Int, y: Int, var r: Int) : Point(x, y) {
    constructor(): this(0, 0, 0)

    constructor(x: Int) : this(x, 0, 0)

    constructor(x: Int, r: Int) : this(x, 0, r)

    constructor(c: Circle) : this(c.x, c.y, c.r)

    // for simplicity not calling super.finalize() below though this would normally be done in practice
    override protected fun finalize() = println("Finalizing $this...")

    override fun toString() = "Circle at center ($x, $y), radius $r"

    override fun print() = println(this)
}

fun createObjects() {
    val points = listOf(Point(), Point(1), Point(2, 3), Point(Point(3, 4)))
    for (point in points) point.print()
    val circles = listOf(Circle(), Circle(1), Circle(2, 3), Circle(4, 5, 6), Circle(Circle(7, 8, 9)))
    for (circle in circles) circle.print()
    println()
}

fun main(args: Array<String>) {
    createObjects()
    System.gc()  // try and force garbage collection
    Thread.sleep(2000) // allow time for finalizers to run
    println()
    val p = Point(5, 6)
    p.print()
    p.y = 7  // change y coordinate
    p.print()
    val c = Circle(5, 6, 7)
    c.print()
    c.r = 8
    c.print() // change radius
    /* note that finalizers for p and c are not called */
}


-- Point
local Point = {x = 0, y = 0}

function Point:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    return o
end

function Point:print()
    print("Point(" .. self.x .. ", " .. self.y .. ")")
end

function Point:copy()
    return Point:new{x = self.x, y = self.y}
end

-- Circle
local Circle = Point:new()
Circle.r = 0

function Circle:print()
    print("Circle(" .. self.x .. ", " .. self.y .. ", " .. self.r .. ")")
end

function Circle:copy()
    return Circle:new{x = self.x, y = self.y, r = self.r}
end


\\ block For This {}, or For object [, object2] { }, where object is a group, or a pointer to group, or an item from an array contains a group
\\ This is "this context".
For This {
\\ any new definition here has a temporary use
\\ can be nested, but if we use object then we can use dots to access members of it. If we use a second one then we have to use double dots (..x for second object, for access to x member)
}