Compound data type: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Added Kotlin)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(73 intermediate revisions by 45 users not shown)
Line 1:
{{task|BasicrBasic language learning}}
{{Data structure}}
 
Line 16:
{{Template:See also lists}}
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">T Point
Int x, y
 
F (x, y)
.x = x
.y = y</syntaxhighlight>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defstructure point
(x (:assert (rationalp x)))
(y (:assert (rationalp y))))
Line 26 ⟶ 34:
(assign p1 (update-point (@ p1) :x 3)) ; Update the x value
(point-x (@ p1))
(point-p (@ p1)) ; Recognizer for points</langsyntaxhighlight>
 
{{out}}
Line 34 ⟶ 42:
3
T</pre>
=={{header|6502 Assembly}}==
 
The method below is a bit unusual compared to [[C]], where each member of a struct is stored consecutively. The addressing modes of 6502 make it much more efficient to store each member of many different structs consecutively. In other words, the index used to offset into <code>point_x</code> represents which instance of the data type the CPU is accessing. Of course, this assumes that you're willing to declare in advance how many active instances of that data type you'll ever have at once, a very frequent practice in the 8-bit assembly world but is absolutely ludicrous in high-level languages.
 
NESASM3 syntax:
<syntaxhighlight lang="6502asm">MAX_POINT_OBJECTS = 64 ; define a constant
 
.rsset $0400 ; reserve memory storage starting at address $0400
point_x .rs MAX_POINT_OBJECTS ; reserve 64 bytes for x-coordinates
point_y .rs MAX_POINT_OBJECTS ; reserve 64 bytes for y-coordinates</syntaxhighlight>
 
VASM syntax:
<syntaxhighlight lang="6502asm">MAX_POINT_OBJECTS equ 64
 
point_ram equ $0400
point_x equ point_ram
point_y equ point_ram+MAX_POINT_OBJECTS</syntaxhighlight>
 
So, for example, let's say we want to load our third (zero-indexed) point variable and copy it to zero page RAM addresses $00 and $01. We would do the following:
<syntaxhighlight lang="6502asm">MAX_POINT_OBJECTS equ 64
 
point_ram equ $0400
point_x equ point_ram
point_y equ point_ram+MAX_POINT_OBJECTS
 
LDX #3
LDA point_x,x
STA $00
LDA point_y,x
STA $01</syntaxhighlight>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
DEFINE REALPTR="CARD"
TYPE PointI=[INT x,y]
TYPE PointR=[REALPTR rx,ry]
 
PROC Main()
PointI p1
PointR p2
REAL realx,realy
 
Put(125) PutE() ;clear screen
 
p1.x=123
p1.y=4567
 
ValR("12.34",realx)
ValR("5.6789",realy)
p2.rx=realx
p2.ry=realy
 
PrintF("Integer point p1=(%I,%I)%E",p1.x,p1.y)
 
Print("Real point p2=(")
PrintR(p2.rx) Print(",")
PrintR(p2.ry) Print(")")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Compound_data_type.png Screenshot from Atari 8-bit computer]
<pre>
Integer point p1=(123,4567)
Real point p2=(12.34,5.6789)
</pre>
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">package
{
public class Point
Line 49 ⟶ 123:
}
}
}</langsyntaxhighlight>
 
=={{header|Ada}}==
===Tagged Type===
Ada tagged types are extensible through inheritance. The reserved word ''tagged'' causes the compiler to create a tag for the type. The tag identifies the position of the type in an inheritance hierarchy.
<langsyntaxhighlight lang="ada">type Point is tagged record
X : Integer := 0;
Y : Integer := 0;
end record;</langsyntaxhighlight>
 
===Record Type===
Ada record types are not extensible through inheritance. Without the reserved word ''tagged'' the record does not belong to an inheritance hierarchy.
<langsyntaxhighlight lang="ada">type Point is record
X : Integer := 0;
Y : Integer := 0;
end record;</langsyntaxhighlight>
 
====Parameterized Types====
An Ada record type can contain a discriminant. The discriminant is used to choose between internal structural representations. Parameterized types were introduced to Ada before tagged types. Inheritance is generally a cleaner solution to multiple representations than is a parameterized type.
<langsyntaxhighlight lang="ada">type Person (Gender : Gender_Type) is record
Name : Name_String;
Age : Natural;
Line 78 ⟶ 152:
null;
end case;
end record;</langsyntaxhighlight>
In this case every person will have the attributes of gender, name, age, and weight. A person with a male gender will also have a beard length.
 
Line 84 ⟶ 158:
===Tagged Type===
ALGOL 68 has only tagged-union/discriminants. And the tagging was strictly done by the ''type'' (MODE) of the members.
<langsyntaxhighlight lang="algol68">MODE UNIONX = UNION(
STRUCT(REAL r, INT i),
INT,
Line 91 ⟶ 165:
STRUCT(REAL rr),
STRUCT([]REAL r)
);</langsyntaxhighlight>
To extract the apropriate member of a UNION a '''conformity-clause''' has to be used.
<langsyntaxhighlight lang="algol68">UNIONX data := 6.6;
CASE data IN
(INT i): printf(($"r: "gl$,i)),
Line 101 ⟶ 175:
OUT
printf($"Other cases"l$)
ESAC;</langsyntaxhighlight>
The '''conformity-clause''' does mean that ALGOL 68 avoids the need for
[[duck typing]], but it also makes the tagged-union kinda tough to use,
Line 108 ⟶ 182:
ALGOL 68 record types are not extensible through inheritance but they
may be part of a larger STRUCT composition.
<langsyntaxhighlight lang="algol68">MODE POINT = STRUCT(
INT x,
INT y
);</langsyntaxhighlight>
====Parameterized Types====
An ALGOL 68 record type can contain a tagged-union/discriminant. The
tagged-union/discriminant is used to choose between internal structural
representations.
<langsyntaxhighlight lang="algol68">MODE PERSON = STRUCT(
STRING name,
REAL age,
Line 124 ⟶ 198:
VOID
) gender details
);</langsyntaxhighlight>
In this case every PERSON will have the attributes of gender details, name, age,
and weight. A PERSON may or may not have a beard. The sex is implied by the tagging.
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% create the compound data type %
record Point( real x, y );
% declare a Point variable %
reference(Point) p;
% assign a value to p %
p := Point( 1, 0.5 );
% access the fields of p - note Algol W uses x(p) where many languages would use p.x %
write( x(p), y(p) )
end.</syntaxhighlight>
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang="amigae">OBJECT point
x, y
ENDOBJECT
Line 142 ⟶ 228:
pt.y := !3.14
END pt
ENDPROC</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* ARM assembly Raspberry PI */
/* program structure.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
 
/*******************************************/
/* Structures */
/********************************************/
.struct 0
point_x: @ x coordinate
.struct point_x + 4
point_y: @ y coordinate
.struct point_y + 4
point_end: @ end structure point
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .ascii "value x : "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
 
 
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
stPoint: .skip point_end @ reservation place in memory
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r1,iAdrstPoint
mov r0,#5 @ x value
str r0,[r1,#point_x]
mov r0,#10 @ y value
str r0,[r1,#point_y]
@ display value
ldr r2,iAdrstPoint
ldr r0,[r2,#point_x]
ldr r1,iAdrsMessValeur
bl conversion10 @ call conversion decimal
ldr r0,iAdrsMessResult
bl affichageMess @ display message
 
 
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrstPoint: .int stPoint
 
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
 
</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">point: #[
x: 10
y: 20
]
 
print point</syntaxhighlight>
 
{{out}}
 
<pre>[x:10 y:20]</pre>
 
=={{header|ATS}}==
 
There are numerous ways to do this. The simplest is to use an "unboxed" tuple type:
 
<syntaxhighlight lang="ats">typedef point (t : t@ype+) = @(t, t)
val p : point double = (1.0, 3.0)</syntaxhighlight>
 
If one insists both that the type be unique (as opposed to an alias for a tuple) and that the notation to create a point be '''Point (x, y)''', then the following works:
<syntaxhighlight lang="ats">datatype point (t : t@ype+) =
| Point of (t, t)
val p : point double = Point (1.0, 3.0)</syntaxhighlight>
 
=={{header|AutoHotkey}}==
Line 148 ⟶ 406:
[[wp:Monkey_patch|monkeypatched]] example.
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">point := Object()
point.x := 1
point.y := 0
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
As usual, arrays are the only data type more complex than a number or a string.<br>
Use quotes around constant strings as element selectors:
<langsyntaxhighlight lang="awk">BEGIN {
p["x"]=10
p["y"]=42
Line 166 ⟶ 424:
for (i in p) print( i, ":", p[i] )
}</langsyntaxhighlight>
{{out}}
<pre>
Line 176 ⟶ 434:
=={{header|Axe}}==
Axe does not have language support for custom data structures. However, they can be implemented from scratch using memory directly.
<langsyntaxhighlight lang="axe">Lbl POINT
r₂→{r₁}ʳ
r₃→{r₁+2}ʳ
r₁
Return</langsyntaxhighlight>
 
To initialize a POINT at memory address L₁ with (x, y) = (5, 10):
<syntaxhighlight lang ="axe">POINT(L₁,5,10)</langsyntaxhighlight>
 
The caller must ensure the buffer has enough free space to contain the object (in this case, 4 bytes).
Line 191 ⟶ 449:
{{works with|PowerBASIC}}
 
<langsyntaxhighlight lang="qb">TYPE Point
x AS INTEGER
y AS INTEGER
END TYPE</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM Point{x%, y%}</langsyntaxhighlight>
 
=={{header|Bracmat}}==
Line 205 ⟶ 463:
So we go object oriented and create a 'type' Point. We show that <code>x</code> and <code>y</code> are independent by changing the value of <code>x</code> and checking that <code>y</code> didn't change.
Bracmat does not have other typing systems than duck typing. The variable <code>Point</code> is not a class, but an object in its own right. The <code>new$</code> function creates a copy of <code>Point</code>.
<langsyntaxhighlight Bracmatlang="bracmat">( ( Point
= (x=)
(y=)
Line 215 ⟶ 473:
& 7:?(pt..x)
& out$(!(pt..x) !(pt..y))
);</langsyntaxhighlight>
{{out}}
<pre>3 4
Line 228 ⟶ 486:
=={{header|C}}==
 
<langsyntaxhighlight lang="c">typedef struct Point
{
int x;
int y;
} Point;</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">struct Point
{
public int x, y;
Line 243 ⟶ 501:
this.y = y;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">struct Point
{
int x;
int y;
};</langsyntaxhighlight>
 
It is also possible to add a constructor (this allows the use of <tt>Point(x, y)</tt> in expressions):
<langsyntaxhighlight lang="cpp">struct Point
{
int x;
int y;
Point(int ax, int ay): x(ax), y(ax) {}
};</langsyntaxhighlight>
 
Point can also be parametrized on the coordinate type:
<langsyntaxhighlight lang="cpp">template<typename Coordinate> struct point
{
Coordinate x, y;
Line 270 ⟶ 528:
 
// a point with floating point coordinates
Point<float> point2 = { 1.7, 3.6 };</langsyntaxhighlight>
Of course, a constructor can be added in this case as well.
 
=={{header|Clean}}==
===Record type===
<langsyntaxhighlight lang="clean">:: Point = { x :: Int, y :: Int }</langsyntaxhighlight>
===Parameterized Algebraic type===
<langsyntaxhighlight lang="clean">:: Point a = Point a a // usage: (Point Int)</langsyntaxhighlight>
===Synonym type===
<langsyntaxhighlight lang="clean">:: Point :== (Int, Int)</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defrecord Point [x y])</langsyntaxhighlight>
This defines a datatype with constructor ''Point.'' and accessors '':x'' and '':y'' :
<langsyntaxhighlight lang="clojure">(def p (Point. 0 1))
(assert (= 0 (:x p)))
(assert (= 1 (:y p)))</langsyntaxhighlight>
 
=={{header|CLU}}==
CLU has two types of compound datatypes: ''struct''s, which are immutable, and ''record''s, which are mutable.
Aside from this, they work the same way.
 
<syntaxhighlight lang="clu">% Definitions
point = struct[x, y: int]
mutable_point = record[x, y: int]
 
% Initialization
p: point := point${x: 10, y: 20}
mp: mutable_point := mutable_point${x: 10, y: 20}</syntaxhighlight>
 
The fields can be accessed using the <code>.</code> syntax:
<syntaxhighlight lang="clu">foo := p.x
bar := p.y</syntaxhighlight>
 
''Record''s, but not ''struct''s, allow updating the fields in the same way.
<syntaxhighlight lang="clu">mp.x := 30
mp.y := 40</syntaxhighlight>
 
It should be noted that the special forms <code>p.x</code> and <code>mp.x := value</code>
are really only syntactic sugar, they are equivalent to the following method calls:
<syntaxhighlight lang="clu">foo := point$get_x(p)
bar := point$get_y(p)</syntaxhighlight>
 
<syntaxhighlight lang="clu">mutable_point$set_x(mp, 30)
mutable_point$set_y(mp, 40)</syntaxhighlight>
 
=={{header|COBOL}}==
A compound data item description is possible in COBOL as a subdivided record:
<syntaxhighlight lang="cobol"> DATA DIVISION.
WORKING-STORAGE SECTION.
01 Point.
05 x USAGE IS BINARY-SHORT.
05 y USAGE IS BINARY-SHORT.</syntaxhighlight>
Here the record <code>Point</code> has the subdivisions <code>x</code> and <code>y</code>, both of which are signed 16-bit binary integers.
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
# Lightweight JS objects (with CS sugar).
point =
Line 310 ⟶ 605:
console.log p1.distance_from # [Function]
console.log p1.distance_from p2 # 13
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">CL-USER> (defstruct point (x 0) (y 0)) ;If not provided, x or y default to 0
POINT</langsyntaxhighlight>
In addition to defining the ''point'' data type, the defstruct macro also created constructor and accessor functions:
<langsyntaxhighlight lang="lisp">CL-USER> (setf a (make-point)) ;The default constructor using the default values for x and y
#S(POINT :X 0 :Y 0)
CL-USER> (setf b (make-point :x 5.5 :y #C(0 1))) ;Dynamic datatypes are the default
Line 328 ⟶ 623:
3
CL-USER> (point-y b)
3</langsyntaxhighlight>
 
=={{header|Crystal}}==
Crystal's structs work very similarly to objects, but are allocated on the stack instead of the heap, and passed by value instead of by reference. More potential caveats are noted in the [https://crystal-lang.org/reference/syntax_and_semantics/structs.html language reference].
 
<syntaxhighlight lang="ruby">struct Point(T)
getter x : T
getter y : T
def initialize(@x, @y)
end
end
 
puts Point(Int32).new 13, 12 #=> Point(Int32)(@x=13, @y=12)</syntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
// A normal POD struct
// (if it's nested and it's not static then it has a hidden
Line 377 ⟶ 684:
static assert(is(p6[0] == int));
static assert(p6[1] == 5);
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
As defined in Types.pas:
 
<langsyntaxhighlight Delphilang="delphi"> TPoint = record
X: Longint;
Y: Longint;
end;
</syntaxhighlight>
</lang>
 
=={{header|Diego}}==
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();
 
add_struct(point)_arg(x,y);
 
with_point(point1)_arg(4,3);
 
// Since no datatype is specified for the args any datatype can be passed
with_point(point2)_arg(0.033,👣);
 
reset_namespace[];</syntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def makePoint(x, y) {
def point {
to getX() { return x }
Line 396 ⟶ 715:
}
return point
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'struct)
(struct Point (x y))
Line 412 ⟶ 731:
(Point 3 'albert)
❌ error: #number? : type-check failure : albert → 'Point:y'
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
Line 418 ⟶ 737:
Ela supports algebraic types:
 
<langsyntaxhighlight lang="ela">type Maybe = None | Some a</langsyntaxhighlight>
 
Except of regular algebraic types, Ela also provides a support for open algebraic types - which can be extended any time with new constructors:
 
<langsyntaxhighlight lang="ela">opentype Several = One | Two | Three
 
//Add new constructor to an existing type
data Several = Four</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 6.x:
<syntaxhighlight lang="elena">struct Point
{
int X : prop;
int Y : prop;
constructor new(int x, int y)
{
X := x;
Y := y
}
}</syntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">iex(1)> defmodule Point do
...(1)> defstruct x: 0, y: 0
...(1)> end
Line 445 ⟶ 779:
10
iex(8)> py
20</langsyntaxhighlight>
 
=={{header|Elm}}==
<syntaxhighlight lang="elm">
--Compound Data type can hold multiple independent values
--In Elm data can be compounded using List, Tuple, Record
--In a List
point = [2,5]
--This creates a list having x and y which are independent and can be accessed by List functions
--Note that x and y must be of same data type
 
--Tuple is another useful data type that stores different independent values
point = (3,4)
--Here we can have multiple data types
point1 = ("x","y")
point2 = (3,4.5)
--The order of addressing matters
--Using a Record is the best option
point = {x=3,y=4}
--To access
point.x
point.y
--Or Use it as a function
.x point
.y point
--Also to alter the value
{point | x=7}
{point | y=2}
{point | x=3,y=4}
--Each time a new record is generated
--END
</syntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(records_test).
-compile(export_all).
Line 459 ⟶ 824:
P2 = P1#point{x=3.0}, % creates a new point record with x set to 3.0, y is copied from P1
io:fwrite("X: ~f, Y: ~f~n",[P2#point.x,P2#point.y]).
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
{{works with|OpenEuphoria}}
<langsyntaxhighlight lang="euphoria">
enum x, y
 
Line 475 ⟶ 840:
printf(1,"x = %d, y = %3.3f\n",point)
printf(1,"x = %s, y = %3.3f\n",point)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 485 ⟶ 850:
=={{header|F_Sharp|F#}}==
See the OCaml section as well. Here we create a list of points and print them out.
<langsyntaxhighlight lang="fsharp">type Point = { x : int; y : int }
 
let points = [
Line 491 ⟶ 856:
{x = 5; y = 5} ]
Seq.iter (fun p -> printfn "%d,%d" p.x p.y) points</langsyntaxhighlight>
 
=={{header|Factor}}==
<syntaxhighlight lang ="factor">TUPLE: point x y ;</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
// define a class to contain the two fields
// accessors to get/set the field values are automatically generated
Line 519 ⟶ 884:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 530 ⟶ 895:
There is no standard structure syntax in Forth, but it is easy to define words for creating and accessing data structures.
 
<langsyntaxhighlight lang="forth">: pt>x ( point -- x ) ;
: pt>y ( point -- y ) CELL+ ;
: .pt ( point -- ) dup pt>x @ . pt>y @ . ; \ or for this simple structure, 2@ . .
Line 536 ⟶ 901:
create point 6 , 0 ,
7 point pt>y !
.pt \ 6 7</langsyntaxhighlight>
 
{{works with|GNU Forth|0.6.2}}
Some Forths have mechanisms for declaring complex structures. For example, GNU Forth uses this syntax:
 
<langsyntaxhighlight lang="forth">struct
cell% field pt>x
cell% field pt>y
end-struct point%</langsyntaxhighlight>
 
=={{header|Fortran}}==
In ISO Fortran 90 or later, use a TYPE declaration, "constructor" syntax, and field delimiter syntax:
<langsyntaxhighlight lang="fortran">program typedemo
type rational ! Type declaration
integer :: numerator
Line 569 ⟶ 934:
oon_denoms = one_over_n%denominator ! Access denominator field in every
! rational array element & store
end program typedemo ! as integer array</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type Point
Line 582 ⟶ 947:
Print p.x, p.y
Print p2.x, p2.y
Sleep</langsyntaxhighlight>
 
{{out}}
Line 590 ⟶ 955:
</pre>
 
=={{header|GoFutureBasic}}==
<syntaxhighlight lang="futurebasic">
<lang go>package main
CGRect r = {0, 0, 250, 100}
printf @"x = %.f : y = %.f : width = %.f : height = %.f", r.origin.x, r.origin.y, r.size.width, r.size.height
 
HandleEvents
import "fmt"
</syntaxhighlight>
{{output}}
<pre>
x = 0 : y = 0 : width = 250 : height = 100
 
</pre>
type point struct {
 
 
=={{header|Go}}==
<syntaxhighlight lang="go">type point struct {
x, y float64
}
</syntaxhighlight>
 
func main() {
fmt.Println(point{3, 4})
}</lang>
 
=={{header|Groovy}}==
 
===Declaration===
<langsyntaxhighlight lang="groovy">class Point {
int x
int y
Line 613 ⟶ 985:
Point(int x = 0, int y = 0) { this.x = x; this.y = y }
String toString() { "{x:${x}, y:${y}}" }
}</langsyntaxhighlight>
 
===Instantiation===
=====Direct=====
<langsyntaxhighlight lang="groovy">// Default Construction with explicit property setting:
def p0 = new Point()
assert 0 == p0.x
Line 633 ⟶ 1,005:
def p2 = new Point(36)
assert 36 == p2.x
assert 0 == p2.y</langsyntaxhighlight>
 
=====List-to-argument Substitution=====
There are several ways that a List can be substituted for constructor arguments via "type coercion" (casting).
<langsyntaxhighlight lang="groovy">// Explicit coersion from list with "as" keyword
def p4 = [36, -2] as Point
assert 36 == p4.x
Line 655 ⟶ 1,027:
Point p8 = [36]
assert 36 == p8.x
assert 0 == p8.y</langsyntaxhighlight>
 
=====Map-to-property Substitution=====
There are several ways to construct an object using a map (or a comma-separated list of map entries) that substitutes entries for class properties. The process is properly (A) instantiation, followed by (B) property mapping. Because the instantiation is not tied to the mapping, it requires the existence of a no-argument constructor.
<langsyntaxhighlight lang="groovy">// Direct map-based construction
def p3 = new Point([x: 36, y: -2])
assert 36 == p3.x
Line 689 ⟶ 1,061:
Point p9 = [y:-2]
assert 0 == p9.x
assert -2 == p9.y</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 729 ⟶ 1,101:
You can make a tuple literal by using a comma-delimited list surrounded by parentheses, without needing to declare the type first:
 
<langsyntaxhighlight lang="haskell">p = (2,3)</langsyntaxhighlight>
 
The type of <code>p</code> is <code>(Int, Int)</code>, using the same comma-delimited list syntax as the literal.
Line 744 ⟶ 1,116:
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang ="icon">record Point(x,y)</langsyntaxhighlight>
 
=={{header|IDL}}==
 
<langsyntaxhighlight lang="idl">point = {x: 6 , y: 0 }
point.y = 7
print, point
;=> { 6 7}</langsyntaxhighlight>
 
 
=={{header|J}}==
Line 758 ⟶ 1,129:
In a "real" J application, points would be represented by arrays of 2 (or N) numbers. None the less, sometimes objects (in the OO sense) are a better representation than arrays, so J supports them:
 
<langsyntaxhighlight lang="j"> NB. Create a "Point" class
coclass'Point'
 
NB. Define its constuctorconstructor
create =: 3 : 0
'X Y' =: y
Line 774 ⟶ 1,145:
10
Y__P
20</langsyntaxhighlight>
 
=={{header|Jakt}}==
<syntaxhighlight lang="jakt">
struct Point {
x: i64
y: i64
}
 
fn main() {
println("{}", Point(x: 3, y: 4))
}
</syntaxhighlight>
 
=={{header|Java}}==
Starting with Java 14 you can use a record
<syntaxhighlight lang="java">
record Point(int x, int y) { }
</syntaxhighlight>
Usage
<syntaxhighlight lang="java">
Point point = new Point(1, 2);
int x = point.x;
int y = point.y;
</syntaxhighlight>
<br />
Alternately
We use a class:
<langsyntaxhighlight lang="java">public class Point
{
public int x, y;
Line 791 ⟶ 1,186:
System.out.println("y = " + point.y );
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
 
<langsyntaxhighlight lang="javascript">//using object literal syntax
var point = {x : 1, y : 2};
 
Line 812 ⟶ 1,207:
}
}
point = new Point(1, 2);</langsyntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">{"x":1, "y":2}</langsyntaxhighlight>
 
If the emphasis in the task description is on "type", then an alternative approach would be to include a "type" key, e.g.
<langsyntaxhighlight lang="jq">{"x":1, "y":2, type: "Point"}</langsyntaxhighlight>
 
Using this approach, one can distinguish between objects of type "Point" and those that happen to have keys named "x" and "y".
Line 824 ⟶ 1,219:
=={{header|JSON}}==
 
<langsyntaxhighlight lang="json">{"x":1,"y":2}</langsyntaxhighlight>
 
=={{header|Julia}}==
'''Define the type''':
<syntaxhighlight lang="julia">struct Point{T<:Real}
<lang Julia>
type Point{T<:Real}
x::T
y::T
end</syntaxhighlight>
end
</lang>
The components of <code>Point</code> can be any sort of real number, though they do have to be of the same type.
 
'''Define a few simple operations for Point''':
<syntaxhighlight lang="julia">Base.:(==)(u::Point, v::Point) = u.x == v.x && u.y == v.y
<lang Julia>
==Base.:-(u::Point, v::Point) = Point(-u.x, == v.x) & (-u.y == v.y)
-Base.:+(u::Point, v::Point) = Point(-u.x + v.x, -u.y + v.y)
+Base.:-(u::Point, v::Point) = Point(u.x + (-v.x, u.y + v.y)</syntaxhighlight>
-(u::Point, v::Point) = Point(u.x - v.x, u.y - v.y)
</lang>
 
'''Have fun''':
<syntaxhighlight lang="julia">a, b, c = Point(1, 2), Point(3, 7), Point(2, 4)
<lang Julia>
@show a b c
a = Point(1, 2)
@show a + b
b = Point(3, 7)
@show -a + b
c = Point(2, 4)
@show a - b
 
println("@show a =+ ",b a)+ c
println("b@show =a ",== b)
@show a + a == c</syntaxhighlight>
println("c = ", c)
 
println("a + b = ", a+b)
println("-a + b = ", -a+b)
println("a - b = ", a-b)
println("a + b + c = ", a+b+c)
println("a == c ", a == c)
println("a + a == c ", a + a == c)
</lang>
 
{{out}}
<pre>a = Point{Int64}(1, 2)
<pre>
ab = Point{Int64}(13,2 7)
bc = Point{Int64}(32,7 4)
ca + b = Point{Int64}(2,4, 9)
-a + b = Point{Int64}(42,9 5)
-a +- b = Point{Int64}(-2, -5)
a -+ b = + c = Point{Int64}(-26,-5 13)
a +== b + c = Point{Int64}(6,13)false
a + a == c = falsetrue</pre>
a + a == c true
</pre>
 
=={{header|KonsolScript}}==
<langsyntaxhighlight KonsolScriptlang="konsolscript">Var:Create(
Point,
Number x,
Number y
)</langsyntaxhighlight>
 
Instanciate it with...
<langsyntaxhighlight KonsolScriptlang="konsolscript">function main() {
Var:Point point;
}</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">data class Point(var x: Int, var y: Int)
<lang scala>// version 1.0.5-2
 
data class Point(var x: Int, var y: Int)
 
fun main(args: Array<String>) {
Line 898 ⟶ 1,277:
p.y = 4
println(p)
}</syntaxhighlight>
}
</lang>
 
{{out}}
Line 906 ⟶ 1,284:
Point(x=3, y=4)
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
1) a pair
{def P {P.new 1 2}}
-> P
{P.left {P}}
-> 1
{P.right {P}}
-> 2
 
2) its Lispsish variant
{def Q {cons 1 2}}
-> Q
{car {Q}}
-> 1
{cdr {Q}}
-> 2
 
3) as an array
{def R {A.new 1 2}}
-> R
{A.first {R}}
-> 1
{A.last {R}}
-> 2
</syntaxhighlight>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
&Point = {
$x
$y
}
</syntaxhighlight>
 
=={{header|Lasso}}==
In Lasso, a point could just be stored in the pair type. However, assuming we want to be able to access the points using the member methods [Point->x] and [Point->y], let's just create a type that inherits from the pair type:
<langsyntaxhighlight lang="lasso">define Point => type {
parent pair
 
Line 922 ⟶ 1,335:
local(point) = Point(33, 42)
#point->x
#point->y</langsyntaxhighlight>
 
{{out}}
Line 932 ⟶ 1,345:
Simply define a record in the LFE REPL (can also be used in include files, modules, etc.):
 
<langsyntaxhighlight lang="lisp">
(defrecord point
x
y)
</syntaxhighlight>
</lang>
 
Creating points:
Line 978 ⟶ 1,391:
=={{header|Lingo}}==
Point and Vector types are built-in. A custom "MyPoint" type can be implemented like this:
<langsyntaxhighlight lang="lingo">-- parent script "MyPoint"
property x
property y
Line 985 ⟶ 1,398:
me.y = py
return me
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">p = script("MyPoint").new(23, 42)
put p.x, p.y
-- 23 42</langsyntaxhighlight>
Construction could also be simplified by using a global wrapper function:
<langsyntaxhighlight lang="lingo">-- in some movie script
on MyPoint (x, y)
return script("MyPoint").new(x, y)
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">p = MyPoint(23, 42)
put p.x, p.y
-- 23 42</langsyntaxhighlight>
 
=={{header|Logo}}==
In Logo, a point is represented by a list of two numbers. For example, this will draw a triangle:
<langsyntaxhighlight lang="logo">setpos [100 100] setpos [100 0] setpos [0 0]
show pos ; [0 0]</langsyntaxhighlight>
Access is via normal list operations like FIRST and BUTFIRST (BF). X is FIRST point, Y is LAST point. For example, a simple drawing program which exits if mouse X is negative:
<langsyntaxhighlight lang="logo">until [(first mousepos) < 0] [ifelse button? [pendown] [penup] setpos mousepos]</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 1,011 ⟶ 1,424:
Lua could use a simple table to store a compound data type Point(x, y):
 
<langsyntaxhighlight lang="lua">
a = {x = 1; y = 2}
b = {x = 3; y = 4}
Line 1,020 ⟶ 1,433:
print(a.x, a.y) --> 1 2
print(c.x, c.y) --> 4 6
</syntaxhighlight>
</lang>
 
==== Prototype Object ====
 
Furthermore, Lua could create a prototype object (OOP class emulation) to represent a compound data type Point(x, y) as the following:
<langsyntaxhighlight lang="lua">
cPoint = {} -- metatable (behaviour table)
function newPoint(x, y) -- constructor
Line 1,035 ⟶ 1,448:
return setmetatable(pointPrototype, cPoint) -- set behaviour and return the pointPrototype
end--newPoint
</syntaxhighlight>
</lang>
 
In the above example, the methods are declared inside the constructor so that they could access the closured values <code>x</code> and <code>y</code> (see usage example). The <code>pointPrototype:type</code> method could be used to extend the original <code>type</code> function available in Lua:
 
<langsyntaxhighlight lang="lua">
local oldtype = type; -- store original type function
function type(v)
Line 1,049 ⟶ 1,462:
end--if vType=="table"
end--type
</syntaxhighlight>
</lang>
 
The usage of metatable <code>cPoint</code> which stores the behavior of the <code>pointPrototype</code> enables additional behaviour to be added to the data type, such as:
 
<langsyntaxhighlight lang="lua">
function cPoint.__add(op1, op2) -- add the x and y components
if type(op1)=="point" and type(op2)=="point" then
Line 1,068 ⟶ 1,481:
end--if type(op1)
end--cPoint.__sub
</syntaxhighlight>
</lang>
 
Usage example:
 
<langsyntaxhighlight lang="lua">
a = newPoint(1, 2)
b = newPoint(3, 4)
Line 1,080 ⟶ 1,493:
print(c:getXY()) --> 4 6
print((a-b):getXY()) --> -2 -2 -- using __sub behaviour
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">Point:= Record(x = 2,y = 4):
 
Point:-x;
Point:-y;</syntaxhighlight>
{{out}}
<pre>
2
4
</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Expressions like point[x, y] can be used without defining.
<langsyntaxhighlight lang="mathematica">In[1]:= a = point[2, 3]
 
Out[1]= point[2, 3]
Line 1,094 ⟶ 1,518:
In[3]:= a[[2]] = 4; a
 
Out[3]= point[2, 4]</langsyntaxhighlight>
 
Or you can just define a function.
<langsyntaxhighlight lang="mathematica">p[x] = 2; p[y] = 3;</langsyntaxhighlight>
Data will be stored as down values of the symbol ''p''.
 
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight MATLABlang="matlab"> point.x=3;
point.y=4;</langsyntaxhighlight>
Alternatively, coordinates can be also stored as vectors
<langsyntaxhighlight MATLABlang="matlab"> point = [3,4];</langsyntaxhighlight>
 
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">defstruct(point(x, y))$
 
p: new(point)$
Line 1,115 ⟶ 1,538:
q: point(1, 2)$
 
p@x: 5$</langsyntaxhighlight>
 
=={{header|MAXScript}}==
Point is a built-in object type in MAX, so...
<langsyntaxhighlight lang="maxscript">struct myPoint (x, y)
newPoint = myPoint x:3 y:4</langsyntaxhighlight>
In practice however, you'd use MAX's built in Point2 type
<langsyntaxhighlight lang="maxscript">newPoint = Point2 3 4</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">Point = {}
Point.x = 0
Point.y = 0</syntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">TYPE Point = RECORD
x, y : INTEGER
END;</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang="modula2">VAR point : Point;
...
point.x := 12;
point.y := 7;</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">TYPE Point = RECORD
x, y: INTEGER;
END;</langsyntaxhighlight>
 
Usage:
Line 1,155 ⟶ 1,583:
=={{header|NetRexx}}==
Like Java, NetRexx uses the <tt>class</tt> instruction to create compound types. Unlike Java; NetRexx provides keywords to automatically generate getters and setters for <tt>class</tt> properties and will automatically generate intermediate methods based on defaults provided in method prototypes.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,177 ⟶ 1,605:
res = 'X='getX()',Y='getY()
return res
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,184 ⟶ 1,612:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">type Point = tuple[x, y: int]
 
var p: Point = (12, 13)
var p2: Point = (x: 100, y: 200)</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
<syntaxhighlight lang="oberon2">
MODULE Point;
TYPE
Object* = POINTER TO ObjectDesc;
ObjectDesc* = RECORD
x-,y-: INTEGER;
END;
 
PROCEDURE (p: Object) Init(x,y: INTEGER);
BEGIN
p.x := x; p.y := y
END Init;
 
PROCEDURE New*(x,y: INTEGER): Object;
VAR
p: Object;
BEGIN
NEW(p);p.Init(x,y);RETURN p;
END New;
 
END Point.
</syntaxhighlight>
 
=={{header|Objeck}}==
Classes are used for compound data types.
<langsyntaxhighlight lang="objeck">
class Point {
@x : Int;
Line 1,227 ⟶ 1,679:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Line 1,234 ⟶ 1,686:
See [[wp:Algebraic_data_type|algebraic data type]]. The different options ("Empty", "Leaf", "Node") are called ''constructors'', and is associated with 0 or more arguments with the declared types; multiple arguments are declared with a syntax that looks like a tuple type, but it is not really a tuple.
 
<langsyntaxhighlight lang="ocaml">type tree = Empty
| Leaf of int
| Node of tree * tree
 
let t1 = Node (Leaf 1, Node (Leaf 2, Leaf 3))</langsyntaxhighlight>
 
===Record Type===
 
<langsyntaxhighlight lang="ocaml">type point = { x : int; y : int }</langsyntaxhighlight>
 
How to construct a point:
 
<langsyntaxhighlight lang="ocaml">let p = { x = 4; y = 5 }</langsyntaxhighlight>
 
You can use the dot (".") to access fields.
<langsyntaxhighlight lang="ocaml">p.x (* evaluates to 4 *)</langsyntaxhighlight>
 
Fields can be optionally declared to be mutable:
<langsyntaxhighlight lang="ocaml">type mutable_point = { mutable x2 : int; mutable y2 : int }</langsyntaxhighlight>
 
Then they can be assigned using the assignment operator "<-"
<langsyntaxhighlight lang="ocaml">let p2 = { x2 = 4; y2 = 5 } in
p2.x2 <- 6;
p2 (* evaluates to { x2 = 6; y2 = 5 } *)</langsyntaxhighlight>
 
===Tuple Type===
Line 1,263 ⟶ 1,715:
You can make a tuple literal by using a comma-delimited list, optionally surrounded by parentheses, without needing to declare the type first:
 
<langsyntaxhighlight lang="ocaml">let p = (2,3)</langsyntaxhighlight>
 
The type of <code>p</code> is a product (indicated by <code>*</code>) of the types of the components:
Line 1,273 ⟶ 1,725:
Using a class :
 
<langsyntaxhighlight lang="oforth">Object Class new: Point(x, y)</langsyntaxhighlight>
 
=={{header|ooRexx}}==
ooRexx uses class for compound data types.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
p = .point~new(3,4)
say "x =" p~x
Line 1,289 ⟶ 1,741:
::attribute x
::attribute y
</syntaxhighlight>
</lang>
 
=={{header|OpenEdge/Progress}}==
Line 1,295 ⟶ 1,747:
The temp-table is a in memory database table. So you can query sort and iterate it, but is the data structure that comes closest.
 
<langsyntaxhighlight Progresslang="progress (Openedgeopenedge ABLabl)">def temp-table point
field x as int
field y as int
.</langsyntaxhighlight>
 
Another option would be a simple class.
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
'SHORT FORM
type point float x,y
 
'FULL FORM
type point
Line 1,312 ⟶ 1,764:
float y
end type
 
</lang>
point p
 
'WITH DEFAULT VALUES
type point
float x = 1.0
float y = 1.0
end type
 
point p = {} 'assigns the set of default values
 
 
print p.x " " p.y
</syntaxhighlight>
 
=={{header|Oz}}==
A point can be represented by using a record value:
<langsyntaxhighlight lang="oz">P = point(x:1 y:2)</langsyntaxhighlight>
 
Now we can access the components by name: P.x and P.y
Often such values are deconstructed by pattern matching:
<langsyntaxhighlight lang="oz">case P of point(x:X y:Y) then
{Show X}
{Show Y}
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">point.x=1;
point.y=2;</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">type point = record
x, y: integer;
end;</langsyntaxhighlight>
 
=={{header|Perl}}==
 
===Array===
<langsyntaxhighlight lang="perl">my @point = (3, 8);</langsyntaxhighlight>
 
===Hash===
<langsyntaxhighlight lang="perl">my %point = (
x => 3,
y => 8
);</langsyntaxhighlight>
 
===Class instance===
<langsyntaxhighlight lang="perl">package Point;
 
use strict;
Line 1,354 ⟶ 1,819:
;
 
my $point = Point->new(x => 3, y => 8);</langsyntaxhighlight>
 
=={{header|Perl 6}}==
{{works with|Rakudo|#24 "Seoul"}}
 
===Array===
<lang perl6>my @point = 3, 8;</lang>
 
===Hash===
<lang perl6>my %point = x => 3, y => 8;</lang>
 
===Class instance===
<lang perl6>class Point { has $.x is rw; has $.y is rw; }
my Point $point .= new(x => 3, y => 8);</lang>
 
===[http://design.perl6.org/S32/Containers.html#Set Set]===
<lang perl6>my $s1 = set <a b c d>; # order is not preserved
my $s2 = set <c d e f>;
say $s1 (&) $s2; # OUTPUT«set(c, e)»
say $s1 ∩ $s2; # we also do Unicode</lang>
 
=={{header|Phix}}==
===traditional user defined type===
The sequence is a natural compound data type. The following would be the same without the type point and declaring p as a sequence, apart from the run-time error. There would be no difficulty defining point to have a string and two atoms.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>enum x,y
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
type point(object p)
<span style="color: #008080;">enum</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span>
return sequence(p) and length(p)=y and atom(p[x]) and atom(p[y])
<span style="color: #008080;">type</span> <span style="color: #000000;">point</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
end type
<span style="color: #008080;">return</span> <span style="color: #004080;">sequence</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">y</span> <span style="color: #008080;">and</span> <span style="color: #004080;">atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">and</span> <span style="color: #004080;">atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">y</span><span style="color: #0000FF;">])</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">type</span>
point p = {175,3.375}
 
<span style="color: #000000;">point</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">175</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3.375</span><span style="color: #0000FF;">}</span>
p[x] -= p[y]*20
<span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">y</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">20</span>
 
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"point p is "</span><span style="color: #0000FF;">)</span>
puts(1,"point p is ")
<span style="color: #0000FF;">?</span><span style="color: #000000;">p</span>
?p
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"p[x]:%g, p[y]:%g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">],</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">y</span><span style="color: #0000FF;">]})</span>
printf(1,"p[x]:%g, p[y]:%g\n",{p[x],p[y]})
<span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- fine</span>
 
<span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">y</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"string"</span> <span style="color: #000080;font-style:italic;">-- run-time error (not pwa/p2js)</span>
p[x] = 0 -- fine
<!--</syntaxhighlight>-->
p[y] = "string" -- run-time error</lang>
{{out}}
<pre>
point p is {107.5,3.375}
p[x]:107.5, p[y]:3.375
 
C:\Program Files (x86)\Phix\test.exw:15
C:\Program Files (x86)\Phix\test.exw:12
type check failure, p is {0,"string"}
 
--> see C:\Program Files (x86)\Phix\ex.err
Press Enter...
</pre>
 
===classes===
{{libheader|Phix/Class}}
You could also use a class (not pwa/p2js)
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">class</span> <span style="color: #000000;">point</span>
<span style="color: #008080;">public</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">class</span>
<span style="color: #000000;">point</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new</span><span style="color: #0000FF;">({</span><span style="color: #000000;">175</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3.375</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">p</span><span style="color: #0000FF;">.</span><span style="color: #000000;">x</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">.</span><span style="color: #000000;">y</span><span style="color: #0000FF;">*</span><span style="color: #000000;">20</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"p.x:%g, p.y:%g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">p</span><span style="color: #0000FF;">.</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">.</span><span style="color: #000000;">y</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">p</span><span style="color: #0000FF;">.</span><span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- fine</span>
<span style="color: #000000;">p</span><span style="color: #0000FF;">.</span><span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"string"</span> <span style="color: #000080;font-style:italic;">-- run-time error</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
p.x:107.5, p.y:3.375
 
C:\Program Files (x86)\Phix\test.exw:9
type error assigning "string" to point.y
 
--> see C:\Program Files (x86)\Phix\ex.err
Press Enter...
</pre>
 
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php"># Using pack/unpack
$point = pack("ii", 1, 2);
 
Line 1,411 ⟶ 1,887:
list($x,$y) = unpack("ii", $point);
echo $x;
echo $y;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="php"># Using array
$point = array('x' => 1, 'y' => 2);
 
Line 1,420 ⟶ 1,896:
 
# or simply:
echo $point['x'], ' ', $point['y'], "\n";</langsyntaxhighlight>
 
<langsyntaxhighlight lang="php"># Using class
class Point {
function __construct($x, $y) { $this->x = $x; $this->y = $y; }
Line 1,428 ⟶ 1,904:
}
$point = new Point(1, 2);
echo $point; # will call __tostring() in later releases of PHP 5.2; before that, it won't work so good.</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(class +Point)
 
(dm T (X Y)
Line 1,439 ⟶ 1,915:
(setq P (new '(+Point) 3 4))
 
(show P)</langsyntaxhighlight>
{{out}}
<pre>$52717735311266 (+Point)
y 4
x 3</pre>
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">
class Point {
int x, y;
void create(int _x, int _y)
{
x = _x;
y = _y;
}
}
 
void main()
{
object point = Point(10, 20);
write("%d %d\n", point->x, point->y);
}
</syntaxhighlight>
{{Out}}
<pre>
10 20
</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
define structure
1 point,
Line 1,453 ⟶ 1,951:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">A cartesian point is a record with an x coord and a y coord.</syntaxhighlight>
 
=={{header|Pop11}}==
 
<langsyntaxhighlight lang="pop11">uses objectclass;
define :class Point;
slot x = 0;
slot y = 0;
enddefine;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
{{works with|PowerShell|5}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
class Point {
[Int]$a
Line 1,484 ⟶ 1,985:
$p1.add()
$p2.mul()
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 1,490 ⟶ 1,991:
6
</pre>
 
=={{header|Prolog}}==
Prolog terms ARE compound data types, there is no need to specifically define a type.
for the purpose of this exercise you could define a rule like so:
<syntaxhighlight lang="prolog">point(10, 20).</syntaxhighlight>
This will create static point that can be called:
<syntaxhighlight lang="prolog">?- point(X,Y).
X = 10,
Y = 20.</syntaxhighlight>
terms can be passed around as values and can have a complex nested structure of any size, eg:
<syntaxhighlight lang="prolog">person_location(person(name(N), age(A)), point(X, Y)).</syntaxhighlight>
 
=={{header|PureBasic}}==
 
A basic [http://www.purebasic.com/documentation/reference/structures.html structure] is implemented as;
<langsyntaxhighlight PureBasiclang="purebasic">Structure MyPoint
x.i
y.i
EndStructure</langsyntaxhighlight>
 
=={{header|Python}}==
 
The simplest way it to use a tuple, or a list if it should be mutable:
<langsyntaxhighlight lang="python">X, Y = 0, 1
p = (3, 4)
p = [3, 4]
 
print p[X]</langsyntaxhighlight>
 
If needed, you can use class:
 
<langsyntaxhighlight lang="python">class Point:
def __init__(self, x=0, y=0):
self.x = x
Line 1,516 ⟶ 2,028:
 
p = Point()
print p.x</langsyntaxhighlight>
 
One could also simply instantiate a generic object and "monkeypatch" it:
 
<langsyntaxhighlight lang="python">class MyObject(object): pass
point = MyObject()
point.x, point.y = 0, 1
# objects directly instantiated from "object()" cannot be "monkey patched"
# however this can generally be done to it's subclasses</langsyntaxhighlight>
 
=== Dictionary ===
Mutable. Can add keys (attributes)
<langsyntaxhighlight lang="python">pseudo_object = {'x': 1, 'y': 2}</langsyntaxhighlight>
 
 
Line 1,535 ⟶ 2,047:
As of Python 2.6 one can use the ''collections.namedtuple'' factory to create classes which associate field names with elements of a tuple. This allows one to perform all normal operations on the contained tuples (access by indices or slices, packing and unpacking) while also allowing elements to be accessed by name.
 
<langsyntaxhighlight lang="python">>>> from collections import namedtuple
>>> help(namedtuple)
Help on function namedtuple in module collections:
Line 1,561 ⟶ 2,073:
Point(x=100, y=22)
 
>>></langsyntaxhighlight>
 
=={{header|QB64}}==
<syntaxhighlight lang="qb64">Type Point
x As Double
y As Double
End Type
 
Dim p As Point
p.x = 15.42
p.y = 2.412
 
Print p.x; p.y</syntaxhighlight>
{{out}}
<pre> 15.42 2.412</pre>
 
=={{header|Quackery}}==
 
The single ubiquitous compound data type in Quackery is the ''nest'' (a ''mostly'' immutable dynamic array), a sequence of items wrapped in square brackets. (''Mostly'' immutable; i.e. immutable except under limited circumstances beyond the scope of this discussion. When we refer to changing the contents of a nest here, this is casual speech; a shorthand for saying "creating a new instance of the nest, identical the previous instance except where it differs".)
 
Presented here are two solutions to the task, the "quick and dirty" solution; sufficient to the task described here, and the "overkill" solution; extending the Quackery compiler to facilitate complex compound data structures akin to structs in C etc.
 
===Quick and Dirty===
 
The word <code>point</code> creates an instance of a nest with two elements, both initialised to zero. The word <code>x</code> specifies the location of the zeroth element within the nest, and the word <code>y</code> specifies the location of the first element within the nest. <code>peek</code> returns the value stored in a specified location, and <code>poke</code> changes the value stored in a specified location, returning the modified nest.
 
<syntaxhighlight lang="quackery">
[ ' [ 0 0 ] ] is point ( --> [ )
 
[ 0 ] is x ( --> n )
 
[ 1 ] is y ( --> n )
 
point
dup x peek echo cr
99 swap y poke
y peek echo cr</syntaxhighlight>
 
{{out}}
 
<pre>0
99</pre>
 
===Overkill===
 
The "overkill" solution automates the process of creating new structures with the word <code>struct{</code>, which extends the Quackery compiler to allow the definition of complex compound data structures as follows.
 
<syntaxhighlight lang="quackery"> struct{
item.0
{ item.1.0
item.1.1
{ item.1.2.0
item.1.2.1
item.1.2.2
item.1.2.3
} item.1.2
item.1.3
} item.1
item.2
}struct mystruct</syntaxhighlight>
 
Once defined, the word <code>mystruct</code> will place a new instance of the described structure, with each item initialised to <code>null</code>, on the stack. (The behaviour of <code>null</code> is to place a reference to itself on the stack, as a convenience for debugging, and to allow code to identify elements within the structure that have not had a value assigned to them.)
 
The various names defined within the struct (e.g. <code>item.1.2.1</code>) return a ''path'' - a means of locating a specific item within the struct, for use by <code>{peek}</code> and <code>{poke}</code>, which have the same behaviours as <code>peek</code> and <code>poke</code>, except the they take a path to an item within a struct as an argument, rather than a number specifying an item within a nest.
 
Names following a <code>}</code> within the definition of a struct (e.g. <code>} item.1.2</code>) return a path to the compound data structure preceding it within the structure. In the example, <code>item.1.2</code> returns the path to <code>{ item.1.2.0 item.1.2.1 item.1.2.2 item.1.2.3 }</code>
 
<syntaxhighlight lang="quackery"> mystruct ( create new instance of a mystruct )
dup echo cr ( this is what it looks like )
789 swap item.1.3 {poke} ( change one of the items )
dup echo cr ( this is what it looks like now )
item.1.3 {peek} echo cr ( retrieve the specified item )
</syntaxhighlight>
 
{{out}}
 
<pre>[ null [ null null [ null null null null ] null ] null ]
[ null [ null null [ null null null null ] 789 ] null ]
789</pre>
 
The words <code>{peek}</code>, <code>{poke}</code>, <code>null</code>, and the building word (i.e. compiler extension) <code>struct{</code> defined:
 
<syntaxhighlight lang="text"> [ witheach peek ] is {peek} ( { p --> x )
 
[ dip dup
witheach [ peek dup ]
drop ] is depack ( { p --> * )
 
[ reverse
witheach
[ dip swap poke ] ] is repack ( * p --> { )
 
[ dup dip
[ rot dip
[ depack drop ] ]
repack ] is {poke} ( x { p --> { )
 
[ this ] is null ( --> [ )
 
[ stack ] is {}.path ( --> s )
protect {}.path
 
[ stack ] is {}.struct ( --> s )
protect {}.struct
 
[ nextword dup
$ "" = if
[ $ "Unexpected end of struct."
message put
bail ] ] is {}.checknext ( [ $ --> [ $ $ )
 
[ dup $ "{" =
over $ "}" = or
swap $ "}struct" = or if
[ $ "Name missing after }."
message put
bail ] ] is {}.checkname ( [ $ $ --> [ $ )
 
[ nested
namenest take
join
namenest put
' [ ' ]
{}.path share nested join
actiontable take
1 stuff
actiontable put ] is {}.addpath ( [ $ $ --> [ $ )
 
[ nested
namenest take
join
namenest put
' [ ' ]
{}.struct share nested join
actiontable take
1 stuff
actiontable put ] is {}.addstruct ( [ $ $ --> [ $ )
 
[ {}.path take
dup -1 peek
1+
swap -1 poke
-1 join
{}.path put
[] {}.struct put ] is {}.{ ( [ $ --> [ $ )
 
[ {}.struct size 3 < if
[ $ "Badly formed struct."
message put bail ]
trim {}.checknext
dup {}.checkname
{}.path take
-1 split drop
{}.path put
{}.addpath
{}.struct take
{}.struct take
swap nested join
{}.struct put ] is {}.} ( [ $ --> [ $ )
 
[ {}.path take
dup -1 peek
1+
swap -1 poke
{}.path put
{}.addpath
{}.struct take
' [ null ] join
{}.struct put ] is {}.name ( [ $ --> [ $ )
 
[ trim {}.checknext
{}.struct size
2 != if
[ $ "Badly formed struct."
message put
bail ]
{}.addstruct ] is {}.}struct ( [ $ --> [ $ )
 
[ ' [ -1 ] {}.path put
[] {}.struct put
[ trim {}.checknext
dup $ "{" = iff
[ drop {}.{ ] again
dup $ "}" = iff
[ drop {}.} ] again
dup $ "}struct" = iff
[ drop {}.}struct ] done
{}.name again ]
{}.struct release
{}.path release ] builds struct{ ( [ $ --> [ $ )</syntaxhighlight>
 
Finally we use <code>struct{</code> etc. to fulfil the requirements go the task.
 
<syntaxhighlight lang="quackery"> struct{ x y }struct point
point
dup x {peek} echo cr
99 swap y {poke}
y {peek} echo cr</syntaxhighlight>
 
{{out}}
 
<pre>null
99
</pre>
 
=={{header|R}}==
R uses the list data type for compound data.
<langsyntaxhighlight Rlang="r">mypoint <- list(x=3.4, y=6.7)
# $x
# [1] 3.4
Line 1,584 ⟶ 2,299:
# [1] 1
# $d$f
# [1] TRUE</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,590 ⟶ 2,305:
The most common method uses structures (similar to records):
 
<langsyntaxhighlight lang="racket">
#lang racket
(struct point (x y))
</syntaxhighlight>
</lang>
 
Alternatively, you can define a class:
 
<langsyntaxhighlight lang="racket">
#lang racket
(define point% ; classes are suffixed with % by convention
Line 1,603 ⟶ 2,318:
(super-new)
(init-field x y)))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|#24 "Seoul"}}
 
===Array===
<syntaxhighlight lang="raku" line>my @point = 3, 8;
 
my Int @point = 3, 8; # or constrain to integer elements</syntaxhighlight>
 
===Hash===
<syntaxhighlight lang="raku" line>my %point = x => 3, y => 8;
 
my Int %point = x => 3, y => 8; # or constrain the hash to have integer values</syntaxhighlight>
 
===Class instance===
<syntaxhighlight lang="raku" line>class Point { has Real ($.x, $.y) is rw; }
my Point $point .= new: x => 3, y => 8;</syntaxhighlight>
 
===[http://design.raku.org/S32/Containers.html#Set Set]===
<syntaxhighlight lang="raku" line>my $s1 = set <a b c d>; # order is not preserved
my $s2 = set <c d e f>;
say $s1 (&) $s2; # OUTPUT«set(c, e)»
say $s1 ∩ $s2; # we also do Unicode</syntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">x= -4.9
y= 1.7
 
point=x y</langsyntaxhighlight>
:: ---or---
<langsyntaxhighlight lang="rexx">x= -4.1
y= 1/4e21
 
Line 1,618 ⟶ 2,357:
bpoint=point
 
gpoint=5.6 7.3e-12</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see new point {x=10 y=20} class point x y
</syntaxhighlight>
</lang>
Output
<langsyntaxhighlight lang="ring">
x: 10.000000
y: 20.000000
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">Point = Struct.new(:x,:y)
pt = Point.new(6,7)
puts pt.x #=> 6
Line 1,645 ⟶ 2,384:
pt.each_pair{|member, value| puts "#{member} : #{value}"}
#=> x : 2
#=> y : 5</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 1,652 ⟶ 2,391:
 
====C-like struct====
<langsyntaxhighlight lang="rust"> // Defines a generic struct where x and y can be of any type T
struct Point<T> {
x: T,
Line 1,660 ⟶ 2,399:
let p = Point { x: 1.0, y: 2.5 }; // p is of type Point<f64>
println!("{}, {}", p.x, p.y);
} </langsyntaxhighlight>
 
====Tuple struct====
These are basically just named tuples.
<langsyntaxhighlight lang="rust">struct Point<T>(T, T);
fn main() {
let p = Point(1.0, 2.5);
println!("{},{}", p.0, p.1);
}</langsyntaxhighlight>
===Tuples===
<langsyntaxhighlight lang="rust"> fn main() {
let p = (0.0, 2.4);
println!("{},{}", p.0, p.1);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">case class Point(x: Int = 0, y: Int = 0)
 
val p = Point(1, 2)
println(p.y) //=> 2</langsyntaxhighlight>
 
=={{header|Scheme}}==
Using [http://srfi.schemers.org/srfi-9/srfi-9.html SRFI 9]:
<langsyntaxhighlight lang="scheme">(define-record-type point
(make-point x y)
point?
(x point-x)
(y point-y))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const type: Point is new struct
var integer: x is 0;
var integer: y is 0;
end struct;</langsyntaxhighlight>
 
=={{header|Shen}}==
<langsyntaxhighlight lang="shen">(datatype point
X : number; Y : number;
====================
[point X Y] : point;)</langsyntaxhighlight>
Pairs (distinct from cons cells) are also supported, in which case a point would be denoted by (number * number):
<langsyntaxhighlight lang="shen">(2+) (@p 1 2)
(@p 1 2) : (number * number)</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">struct Point {x, y};
var point = Point(1, 2);
say point.y; #=> 2</langsyntaxhighlight>
 
=={{header|SIMPOL}}==
The <code>point</code> type is pre-defined in [SIMPOL], so we will call this mypoint.
 
<langsyntaxhighlight lang="simpol">type mypoint
embed
integer x
integer y
end type</langsyntaxhighlight>
 
The <code>embed</code> keyword is used here as a toggle to indicate that all following properties are embedded in the type. The other toggle is <code>reference</code>, which only places a reference to an object in the type, but the reference assigned before the property can be used. These keywords can also be placed on the same line, but then they only apply to that line of the type definition.
Line 1,722 ⟶ 2,461:
A type in [SIMPOL] can be just a container of values and other structures, but it can also include methods. These are implemented outside the type definition, but must be part of the same compiled unit.
 
<langsyntaxhighlight lang="simpol">type mypoint
embed
integer x
Line 1,731 ⟶ 2,470:
me.x = x
me.y = y
end function me</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
 
<langsyntaxhighlight lang="snobol"> data('point(x,y)')
p1 = point(10,20)
p2 = point(10,40)
output = "Point 1 (" x(p1) "," y(p1) ")"
output = "Point 2 (" x(p2) "," y(p2) ")"
end</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Line 1,747 ⟶ 2,486:
See [[wp:Algebraic_data_type|algebraic data type]]. The different options ("Empty", "Leaf", "Node") are called ''constructors'', and is associated with 0 or 1 arguments with the declared types; multiple arguments are handled with tuples.
 
<langsyntaxhighlight lang="sml">datatype tree = Empty
| Leaf of int
| Node of tree * tree
 
val t1 = Node (Leaf 1, Node (Leaf 2, Leaf 3))</langsyntaxhighlight>
 
===Tuple Type===
Line 1,757 ⟶ 2,496:
You can make a tuple literal by using a comma-delimited list surrounded by parentheses, without needing to declare the type first:
 
<langsyntaxhighlight lang="sml">val p = (2,3)</langsyntaxhighlight>
 
The type of <code>p</code> is a product (indicated by <code>*</code>) of the types of the components:
Line 1,774 ⟶ 2,513:
You can make a record literal by using a comma-delimited list of <code>key = value</code> pairs surrounded by curly braces, without needing to declare the type first:
 
<langsyntaxhighlight lang="sml">val p = { x = 4, y = 5 }</langsyntaxhighlight>
 
The type of <code>p</code> is a comma-delimited list of <code>key:type</code> pairs of the types of the fields:
Line 1,784 ⟶ 2,523:
val it = 5 : int
The <code>#y</code> above extracts the field named "y" of its argument.
 
=={{header|Stata}}==
See '''[https://www.stata.com/help.cgi?m2_struct struct]''' in Stata help.
 
<syntaxhighlight lang="stata">mata
struct Point {
real scalar x, y
}
 
// dumb example
function test() {
struct Point scalar a
a.x = 10
a.y = 20
printf("%f\n",a.x+a.y)
}
 
test()
30
end</syntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">// Structure
struct Point {
var x:Int
Line 1,804 ⟶ 2,563:
self.y = y
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
This can be done using an associative array:
<langsyntaxhighlight lang="tcl">array set point {x 4 y 5}
set point(y) 7
puts "Point is {$point(x),$point(y)}"
# => Point is {4,7}</langsyntaxhighlight>
Or a dictionary:
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">set point [dict create x 4 y 5]
dict set point y 7
puts "Point is {[dict get $point x],[dict get $point y]}"</langsyntaxhighlight>
Or an object:
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">oo::class create Point {
variable x y
constructor {X Y} {set x $X;set y $Y}
Line 1,828 ⟶ 2,587:
Point create point 4 5
point y 7
puts "Point is [point show]"</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
TI-89 BASIC does not have user-defined data structures. The specific example of a point is best handled by using the built-in vectors or complex numbers.
 
=={{header|Transd}}==
<syntaxhighlight lang="Scheme">#lang transd
 
// If the Point type needs encapsulation and/or methods, it should be
// implemented as class. Otherwise, the named tuple will do.
 
class Point: {
x: Double(), y: Double(),
@init: (λ _x Double() _y Double() (= x _x) (= y _y)),
@to-String: (λ ss StringStream() (textout to: ss
"Point( x: " x "; y: " y " )"))
// ... other methods can be defined here ...
}
 
MainModule: {
Point2: typealias(Tuple<Double Double>()),
_start: (λ
(with pt Point(2.5 3.7)
(lout "Class: " pt)
)
(with pt Point2(2.5 3.7)
(lout "\nNamed tuple: " pt)
)
)
}</syntaxhighlight>
{{out}}
<pre>
Class: Point( x: 2.5; y: 3.7 )
 
Named tuple: [[2.5, 3.7]]
</pre>
 
=={{header|TXR}}==
Line 1,838 ⟶ 2,629:
In TXR Lisp, a structure type can be created:
 
<langsyntaxhighlight lang="txrlisp">(defstruct point nil (x 0) (y 0))</langsyntaxhighlight>
 
If it is okay for the coordinates to be initialized to <tt>nil</tt>, it can be condensed to:
 
<langsyntaxhighlight lang="txrlisp">(defstruct point nil x y)</langsyntaxhighlight>
 
The <tt>nil</tt> denotes that a <tt>point</tt> has no supertype: it doesn't inherit from anything.
Line 1,848 ⟶ 2,639:
This structure type can then be instantiated using the <tt>new</tt> macro (not the only way):
 
<langsyntaxhighlight lang="txrlisp">(new point) ;; -> #S(point x 0 y 0)
(new point x 1) ;; -> #S(point x 1 y 0)
(new point x 1 y 1) ;; -> #S(point x 1 y 1)</langsyntaxhighlight>
 
A structure can support optional by-order-of-arguments ("boa") construction by providing a "boa constructor". The <tt>defstruct</tt> syntactic sugar does this if a function-like syntax is used in place of the structure name:
 
<langsyntaxhighlight lang="txrlisp">(defstruct (point x y) nil (x 0) (y 0))</langsyntaxhighlight>
 
The existing construction methods continue to work, but in addition, this is now possible:
 
<langsyntaxhighlight lang="txrlisp">(new (point 3 4)) -> #S(point x 3 y 4)</langsyntaxhighlight>
 
Slot access syntax is supported. If variable <tt>p</tt> holds a point, then <tt>p.x</tt> designates the <tt>x</tt> slot, as a syntactic place which can be accessed and stored:
 
<langsyntaxhighlight lang="txrlisp">(defun displace-point-destructively (p delta)
(inc p.x delta.x)
(inc p.y delta.y))</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|ksh93}}
ksh93 allows you to define new compound types with the <tt>typeset -T</tt> command.
<langsyntaxhighlight lang="bash">typeset -T Point=(
typeset x
typeset y
Line 1,879 ⟶ 2,670:
echo ${p.x} ${p.y}
Point q=(x=3 y=4)
echo ${q.x} ${q.y}</langsyntaxhighlight>
{{out}}
<pre>( x=1 y=2 )
Line 1,886 ⟶ 2,677:
 
You can also declare compound variables "on the fly" without using a defined type:
<langsyntaxhighlight lang="bash">point=()
point.x=5
point.y=6
echo $point
echo ${point.x} ${point.y}</langsyntaxhighlight>
{{out}}
<pre>( x=5 y=6 )
Line 1,897 ⟶ 2,688:
=={{header|Ursala}}==
A record type with two untyped fields named <code>x</code> and <code>y</code> can be declared like this.
<syntaxhighlight lang Ursala="ursala">point :: x y</langsyntaxhighlight>
A constant instance of the record can be declared like this.
<langsyntaxhighlight Ursalalang="ursala">p = point[x: 'foo',y: 'bar']</langsyntaxhighlight>
A function returning a value of this type can be defined like this,
<langsyntaxhighlight Ursalalang="ursala">f = point$[x: g,y: h]</langsyntaxhighlight>
where <code>g</code> and <code>h</code> are functions. Then <code>f(p)</code> would evaluate to
<code>point[x: g(p),y: h(p)]</code> for a given argument <code>p</code>. Accessing the fields of
a record can be done like this.
<langsyntaxhighlight Ursalalang="ursala">t = ~x p
u = ~y p</langsyntaxhighlight>
where <code>p</code> is any expression of the defined type. A real application wouldn't be written
this way because pairs of values <code>(x,y)</code> are a common idiom.
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">struct Point {
int x;
int y;
}</syntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Type point
x As Integer
y As Integer
End Type</syntaxhighlight>
 
=={{header|Vim Script}}==
One cannot create new data types in Vim Script. A point could be represented by a dictionary:
 
<langsyntaxhighlight lang="vim">function MakePoint(x, y) " 'Constructor'
return {"x": a:x, "y": a:y}
endfunction
Line 1,921 ⟶ 2,724:
 
echon "Point 1: x = " p1.x ", y = " p1.y "\n"
echon "Point 2: x = " p2.x ", y = " p2.y "\n"</langsyntaxhighlight>
 
{{Out}}
Line 1,929 ⟶ 2,732:
=={{header|Visual Basic .NET}}==
 
=== Simple Structures ===
 
This shows a structure in its simpest form.
 
A simple structure with two public, mutable fields:
<lang vbnet>Structure Simple_Point
<syntaxhighlight lang="vbnet">Structure Point
Public X, Y As Integer
End Structure</langsyntaxhighlight>
 
=== Immutable Structures ===
 
It is generally recommended in .NET that mutable structures only be used in niche cases where they provide needed performance, e.g. when the creation of massive numbers of class instances would cause excessive garbage collection pressure, as high-performance code dealing with structs generally is of a paradigm considered "impure" from an object-oriented perspective that relies on passing by reference and directly exposing fields.
In Visual Basic, mutable strucutures are difficult to use properly and should only be used when performance measurements warrant it. The rest of the time, immutable structures should be used. Below is the same structure seen before, but in an immutable form.
 
The semantics of value types in .NET mean that a new copy of a structure is created whenever one is passed by value to or from a method or property. This is particularly vexing when properties are involved, as it is not possible to mutate a structure that is returned by a property, due to the returned structure actually being an independent copy of whatever the property originally returned. The only workaround would be to store the value of the property in a temporary variable, mutate that variable, and assign the mutated variable back to the property, which involves another copy operation. When a structure is large, this copying can significantly affect performance.
<lang vbnet>Structure Immutable_Point
Private m_X As Integer
Private m_Y As Integer
 
On another note, algorithms relying on immutable data structures are often more easily parallelized, as they eliminate the race conditions caused by concurrent reading and writing.
Public Sub New(ByVal x As Integer, ByVal y As Integer)
 
m_X = x
Below is the same <code>Point</code> as above, except with an immutable API.
m_Y = y
 
<syntaxhighlight lang="vbnet">Structure ImmutablePoint
ReadOnly Property X As Integer
ReadOnly Property Y As Integer
 
Public Sub New(x As Integer, y As Integer)
Me.X = x
Me.Y = y
End Sub
End Structure</syntaxhighlight>
 
=={{header|V (Vlang)}}==
Public ReadOnly Property X() As Integer
Vlang also supports embedding structs into other structs and assigning methods to structs.
Get
<syntaxhighlight lang="v (vlang)">struct Point {
Return m_X
x End Getint
End Propertyy int
}
 
// main() declaration can be skipped in one file programs
Public ReadOnly Property Y() As Integer
// we can define whether immutable or mutable by using the "mut" keyword
Get
Return m_Y
End Get
End Property
 
mut p := Point{
End Structure</lang>
x: 10
y: 20
}
 
// struct fields are accessed using a dot
 
println("Value of p.x is: $p.x")
println("Show the struct:\n $p")
 
// alternative literal syntax can be used for structs with 3 fields or fewer
 
p = Point{30, 40}
assert p.x == 30
println("Show the struct again after change:\n $p")
</syntaxhighlight>
{{out}}
<pre>
Value of p.x is: 10
Show the struct:
Point{
x: 10
y: 20
}
Show the struct again after change:
Point{
x: 30
y: 40
}
</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">class Point {
construct new(x, y) {
_x = x
_y = y
}
x { _x }
y { _y }
 
// for illustration allow Points to be mutated
x=(value) { _x = value }
y=(value) { _y = value }
 
toString { "(%(_x), %(_y))" }
}
 
var p = Point.new(1, 2)
System.print(p.toString)
 
// mutate Point object
p.x = 2
p.y = 3
// print without using the toString method
System.printAll(["(", p.x, ", ", p.y, ")"])</syntaxhighlight>
 
{{out}}
<pre>
(1, 2)
(2, 3)
</pre>
 
=={{header|XSLT}}==
Line 1,969 ⟶ 2,836:
===Attributes===
Attributes are often used for simple values. This is how a point might be represented in SVG, for example.
<langsyntaxhighlight lang="xml"><point x="20" y="30"/>
 
<!-- context is a point node. The '@' prefix selects named attributes of the current node. -->
<fo:block>Point = <xsl:value-of select="@x"/>, <xsl:value-of select="@y"/></fo:block></langsyntaxhighlight>
 
===Children===
More complex, multivariate, and nested data structures can be represented using child nodes.
<langsyntaxhighlight lang="xml"><circle>
<point>
<x>20</x>
Line 1,984 ⟶ 2,851:
</circle>
 
<!-- context is a circle node. Children are accessed using a path-like notation (hence the name "XPath"). --></langsyntaxhighlight>
<fo:block>Circle center = <xsl:value-of select="point/x"/>, <xsl:value-of select="point/y"/></fo:block>
 
=={{header|Z80 Assembly}}==
We'll declare the following C struct:
<syntaxhighlight lang="c">struct Point{
char x;
char y;
}</syntaxhighlight>
 
and then execute the following C code as Z80 Assembly below.
<syntaxhighlight lang="c">struct Point myPoint;
myPoint.x = 3;
myPoint.y = 5;</syntaxhighlight>
 
<syntaxhighlight lang="z80">;I'm arbitrarily choosing &1100 as the memory location of our Point variable.
ld hl,&1100
ld (hl),3
inc hl
ld (hl),5
ret</syntaxhighlight>
 
=={{header|zkl}}==
The OO solution:
<langsyntaxhighlight lang="zkl">class Point{ var x,y;
fcn init(x,y){self.x=x.toFloat(); self.y=y.toFloat(); }
fcn toString{ "P(%f,%f)".fmt(x,y) }
Line 1,995 ⟶ 2,881:
//... __opEQ == etc
}
Point(1,2).println() //-->P(1.000000,2.000000)</langsyntaxhighlight>
which can be pretty heavy weight. [read only] lists can work just as well:
<langsyntaxhighlight lang="zkl">point:=T(1,2); points:=T( T(1,2), L(3,4) )</langsyntaxhighlight>
 
{{omit from|bc}}
{{omit from|dc}}
 
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
{ref,public} (* class *)
Point = object(ord,abs: integer)
var
(* instance variables *)
{public,immutable} x,y: integer;
 
(* method *)
procedure {public} Ord():integer;
begin
return y
end Ord;
 
(* method *)
procedure {public} Abs():integer;
begin
return x
end Abs;
 
(* constructor *)
begin
self.x := ord;
self.y := abs;
end Point;
</syntaxhighlight>
9,476

edits