Compound data type: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
Thundergnat (talk | contribs) m (Fix Perl6 -> Raku links) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(45 intermediate revisions by 27 users not shown) | |||
Line 1:
{{task|
{{Data structure}}
Line 18:
=={{header|11l}}==
<
Int x, y
F (x, y)
.x = x
.y = y</
=={{header|ACL2}}==
<
(x (:assert (rationalp x)))
(y (:assert (rationalp y))))
Line 34:
(assign p1 (update-point (@ p1) :x 3)) ; Update the x value
(point-x (@ p1))
(point-p (@ p1)) ; Recognizer for points</
{{out}}
Line 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}}==
<
{
public class Point
Line 57 ⟶ 123:
}
}
}</
=={{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.
<
X : Integer := 0;
Y : Integer := 0;
end record;</
===Record Type===
Ada record types are not extensible through inheritance. Without the reserved word ''tagged'' the record does not belong to an inheritance hierarchy.
<
X : Integer := 0;
Y : Integer := 0;
end record;</
====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.
<
Name : Name_String;
Age : Natural;
Line 86 ⟶ 152:
null;
end case;
end record;</
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 92 ⟶ 158:
===Tagged Type===
ALGOL 68 has only tagged-union/discriminants. And the tagging was strictly done by the ''type'' (MODE) of the members.
<
STRUCT(REAL r, INT i),
INT,
Line 99 ⟶ 165:
STRUCT(REAL rr),
STRUCT([]REAL r)
);</
To extract the apropriate member of a UNION a '''conformity-clause''' has to be used.
<
CASE data IN
(INT i): printf(($"r: "gl$,i)),
Line 109 ⟶ 175:
OUT
printf($"Other cases"l$)
ESAC;</
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 116 ⟶ 182:
ALGOL 68 record types are not extensible through inheritance but they
may be part of a larger STRUCT composition.
<
INT x,
INT y
);</
====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.
<
STRING name,
REAL age,
Line 132 ⟶ 198:
VOID
) gender details
);</
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}}==
<
% create the compound data type %
record Point( real x, y );
Line 146 ⟶ 212:
% access the fields of p - note Algol W uses x(p) where many languages would use p.x %
write( x(p), y(p) )
end.</
=={{header|AmigaE}}==
<
x, y
ENDOBJECT
Line 162 ⟶ 228:
pt.y := !3.14
END pt
ENDPROC</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 309 ⟶ 375:
iMagicNumber: .int 0xCCCCCCCD
</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">point: #[
x: 10
]
print point</
{{out}}
<pre>
==
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 349 ⟶ 406:
[[wp:Monkey_patch|monkeypatched]] example.
<
point.x := 1
point.y := 0
</syntaxhighlight>
=={{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:
<
p["x"]=10
p["y"]=42
Line 367 ⟶ 424:
for (i in p) print( i, ":", p[i] )
}</
{{out}}
<pre>
Line 377 ⟶ 434:
=={{header|Axe}}==
Axe does not have language support for custom data structures. However, they can be implemented from scratch using memory directly.
<
r₂→{r₁}ʳ
r₃→{r₁+2}ʳ
r₁
Return</
To initialize a POINT at memory address L₁ with (x, y) = (5, 10):
<syntaxhighlight lang
The caller must ensure the buffer has enough free space to contain the object (in this case, 4 bytes).
Line 392 ⟶ 449:
{{works with|PowerBASIC}}
<
x AS INTEGER
y AS INTEGER
END TYPE</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
=={{header|Bracmat}}==
Line 406 ⟶ 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>.
<
= (x=)
(y=)
Line 416 ⟶ 473:
& 7:?(pt..x)
& out$(!(pt..x) !(pt..y))
);</
{{out}}
<pre>3 4
Line 429 ⟶ 486:
=={{header|C}}==
<
{
int x;
int y;
} Point;</
=={{header|C sharp|C#}}==
<
{
public int x, y;
Line 444 ⟶ 501:
this.y = y;
}
}</
=={{header|C++}}==
<
{
int x;
int y;
};</
It is also possible to add a constructor (this allows the use of <tt>Point(x, y)</tt> in expressions):
<
{
int x;
int y;
Point(int ax, int ay): x(ax), y(ax) {}
};</
Point can also be parametrized on the coordinate type:
<
{
Coordinate x, y;
Line 471 ⟶ 528:
// a point with floating point coordinates
Point<float> point2 = { 1.7, 3.6 };</
Of course, a constructor can be added in this case as well.
=={{header|Clean}}==
===Record type===
<
===Parameterized Algebraic type===
<
===Synonym type===
<
=={{header|Clojure}}==
<
This defines a datatype with constructor ''Point.'' and accessors '':x'' and '':y'' :
<
(assert (= 0 (:x p)))
(assert (= 1 (:y p)))</
=={{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.
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}}==
<
# Lightweight JS objects (with CS sugar).
point =
Line 518 ⟶ 605:
console.log p1.distance_from # [Function]
console.log p1.distance_from p2 # 13
</syntaxhighlight>
=={{header|Common Lisp}}==
<
POINT</
In addition to defining the ''point'' data type, the defstruct macro also created constructor and accessor functions:
<
#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 536 ⟶ 623:
3
CL-USER> (point-y b)
3</
=={{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}}==
<
// A normal POD struct
// (if it's nested and it's not static then it has a hidden
Line 585 ⟶ 684:
static assert(is(p6[0] == int));
static assert(p6[1] == 5);
}</
=={{header|Delphi}}==
As defined in Types.pas:
<
X: Longint;
Y: Longint;
end;
</syntaxhighlight>
=={{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}}==
<
def point {
to getX() { return x }
Line 604 ⟶ 715:
}
return point
}</
=={{header|EchoLisp}}==
<
(lib 'struct)
(struct Point (x y))
Line 620 ⟶ 731:
(Point 3 'albert)
❌ error: #number? : type-check failure : albert → 'Point:y'
</syntaxhighlight>
=={{header|Ela}}==
Line 626 ⟶ 737:
Ela supports algebraic types:
<
Except of regular algebraic types, Ela also provides a support for open algebraic types - which can be extended any time with new constructors:
<
//Add new constructor to an existing type
data Several = Four</
=={{header|Elena}}==
ELENA 6.x:
<syntaxhighlight lang="elena">struct Point
{
constructor new(int x, int y)
Line 647 ⟶ 759:
Y := y
}
}</
=={{header|Elixir}}==
<
...(1)> defstruct x: 0, y: 0
...(1)> end
Line 667 ⟶ 779:
10
iex(8)> py
20</
=={{header|Elm}}==
<
--Compound Data type can hold multiple independent values
--In Elm data can be compounded using List, Tuple, Record
Line 698 ⟶ 810:
--Each time a new record is generated
--END
</syntaxhighlight>
=={{header|Erlang}}==
<
-module(records_test).
-compile(export_all).
Line 712 ⟶ 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>
=={{header|Euphoria}}==
{{works with|OpenEuphoria}}
<
enum x, y
Line 728 ⟶ 840:
printf(1,"x = %d, y = %3.3f\n",point)
printf(1,"x = %s, y = %3.3f\n",point)
</syntaxhighlight>
{{out}}
<pre>
Line 738 ⟶ 850:
=={{header|F_Sharp|F#}}==
See the OCaml section as well. Here we create a list of points and print them out.
<
let points = [
Line 744 ⟶ 856:
{x = 5; y = 5} ]
Seq.iter (fun p -> printfn "%d,%d" p.x p.y) points</
=={{header|Factor}}==
<syntaxhighlight lang
=={{header|Fantom}}==
<
// define a class to contain the two fields
// accessors to get/set the field values are automatically generated
Line 772 ⟶ 884:
}
}
</syntaxhighlight>
{{out}}
Line 783 ⟶ 895:
There is no standard structure syntax in Forth, but it is easy to define words for creating and accessing data structures.
<
: pt>y ( point -- y ) CELL+ ;
: .pt ( point -- ) dup pt>x @ . pt>y @ . ; \ or for this simple structure, 2@ . .
Line 789 ⟶ 901:
create point 6 , 0 ,
7 point pt>y !
.pt \ 6 7</
{{works with|GNU Forth|0.6.2}}
Some Forths have mechanisms for declaring complex structures. For example, GNU Forth uses this syntax:
<
cell% field pt>x
cell% field pt>y
end-struct point%</
=={{header|Fortran}}==
In ISO Fortran 90 or later, use a TYPE declaration, "constructor" syntax, and field delimiter syntax:
<
type rational ! Type declaration
integer :: numerator
Line 822 ⟶ 934:
oon_denoms = one_over_n%denominator ! Access denominator field in every
! rational array element & store
end program typedemo ! as integer array</
=={{header|FreeBASIC}}==
<
Type Point
Line 835 ⟶ 947:
Print p.x, p.y
Print p2.x, p2.y
Sleep</
{{out}}
Line 843 ⟶ 955:
</pre>
=={{header|
<syntaxhighlight lang="futurebasic">
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
</syntaxhighlight>
{{output}}
<pre>
x = 0 : y = 0 : width = 250 : height = 100
</pre>
=={{header|Go}}==
<syntaxhighlight lang="go">type point struct {
x, y float64
}
</syntaxhighlight>
=={{header|Groovy}}==
===Declaration===
<
int x
int y
Line 866 ⟶ 985:
Point(int x = 0, int y = 0) { this.x = x; this.y = y }
String toString() { "{x:${x}, y:${y}}" }
}</
===Instantiation===
=====Direct=====
<
def p0 = new Point()
assert 0 == p0.x
Line 886 ⟶ 1,005:
def p2 = new Point(36)
assert 36 == p2.x
assert 0 == p2.y</
=====List-to-argument Substitution=====
There are several ways that a List can be substituted for constructor arguments via "type coercion" (casting).
<
def p4 = [36, -2] as Point
assert 36 == p4.x
Line 908 ⟶ 1,027:
Point p8 = [36]
assert 36 == p8.x
assert 0 == p8.y</
=====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.
<
def p3 = new Point([x: 36, y: -2])
assert 36 == p3.x
Line 942 ⟶ 1,061:
Point p9 = [y:-2]
assert 0 == p9.x
assert -2 == p9.y</
=={{header|Haskell}}==
Line 982 ⟶ 1,101:
You can make a tuple literal by using a comma-delimited list surrounded by parentheses, without needing to declare the type first:
<
The type of <code>p</code> is <code>(Int, Int)</code>, using the same comma-delimited list syntax as the literal.
Line 997 ⟶ 1,116:
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang
=={{header|IDL}}==
<
point.y = 7
print, point
;=> { 6 7}</
=={{header|J}}==
Line 1,010 ⟶ 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:
<
coclass'Point'
NB. Define its
create =: 3 : 0
'X Y' =: y
Line 1,026 ⟶ 1,145:
10
Y__P
20</
=={{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:
<
{
public int x, y;
Line 1,043 ⟶ 1,186:
System.out.println("y = " + point.y );
}
}</
=={{header|JavaScript}}==
<
var point = {x : 1, y : 2};
Line 1,064 ⟶ 1,207:
}
}
point = new Point(1, 2);</
=={{header|jq}}==
<
If the emphasis in the task description is on "type", then an alternative approach would be to include a "type" key, e.g.
<
Using this approach, one can distinguish between objects of type "Point" and those that happen to have keys named "x" and "y".
Line 1,076 ⟶ 1,219:
=={{header|JSON}}==
<
=={{header|Julia}}==
'''Define the type''':
<
x::T
y::T
end</
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''':
<
Base.:-(u::Point) = Point(-u.x, -u.y)
Base.:+(u::Point, v::Point) = Point(u.x + v.x, u.y + v.y)
Base.:-(u::Point, v::Point) = u + (-v)</
'''Have fun''':
<
@show a b c
@show a + b
Line 1,100 ⟶ 1,243:
@show a + b + c
@show a == b
@show a + a == c</
{{out}}
Line 1,114 ⟶ 1,257:
=={{header|KonsolScript}}==
<
Point,
Number x,
Number y
)</
Instanciate it with...
<
Var:Point point;
}</
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,134 ⟶ 1,277:
p.y = 4
println(p)
}</
{{out}}
Line 1,141 ⟶ 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:
<
parent pair
Line 1,157 ⟶ 1,335:
local(point) = Point(33, 42)
#point->x
#point->y</
{{out}}
Line 1,167 ⟶ 1,345:
Simply define a record in the LFE REPL (can also be used in include files, modules, etc.):
<
(defrecord point
x
y)
</syntaxhighlight>
Creating points:
Line 1,213 ⟶ 1,391:
=={{header|Lingo}}==
Point and Vector types are built-in. A custom "MyPoint" type can be implemented like this:
<
property x
property y
Line 1,220 ⟶ 1,398:
me.y = py
return me
end</
<
put p.x, p.y
-- 23 42</
Construction could also be simplified by using a global wrapper function:
<
on MyPoint (x, y)
return script("MyPoint").new(x, y)
end</
<
put p.x, p.y
-- 23 42</
=={{header|Logo}}==
In Logo, a point is represented by a list of two numbers. For example, this will draw a triangle:
<
show pos ; [0 0]</
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:
<
=={{header|Lua}}==
Line 1,246 ⟶ 1,424:
Lua could use a simple table to store a compound data type Point(x, y):
<
a = {x = 1; y = 2}
b = {x = 3; y = 4}
Line 1,255 ⟶ 1,433:
print(a.x, a.y) --> 1 2
print(c.x, c.y) --> 4 6
</syntaxhighlight>
==== Prototype Object ====
Furthermore, Lua could create a prototype object (OOP class emulation) to represent a compound data type Point(x, y) as the following:
<
cPoint = {} -- metatable (behaviour table)
function newPoint(x, y) -- constructor
Line 1,270 ⟶ 1,448:
return setmetatable(pointPrototype, cPoint) -- set behaviour and return the pointPrototype
end--newPoint
</syntaxhighlight>
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:
<
local oldtype = type; -- store original type function
function type(v)
Line 1,284 ⟶ 1,462:
end--if vType=="table"
end--type
</syntaxhighlight>
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:
<
function cPoint.__add(op1, op2) -- add the x and y components
if type(op1)=="point" and type(op2)=="point" then
Line 1,303 ⟶ 1,481:
end--if type(op1)
end--cPoint.__sub
</syntaxhighlight>
Usage example:
<
a = newPoint(1, 2)
b = newPoint(3, 4)
Line 1,315 ⟶ 1,493:
print(c:getXY()) --> 4 6
print((a-b):getXY()) --> -2 -2 -- using __sub behaviour
</syntaxhighlight>
=={{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.
<
Out[1]= point[2, 3]
Line 1,329 ⟶ 1,518:
In[3]:= a[[2]] = 4; a
Out[3]= point[2, 4]</
Or you can just define a function.
<
Data will be stored as down values of the symbol ''p''.
=={{header|MATLAB}} / {{header|Octave}}==
<
point.y=4;</
Alternatively, coordinates can be also stored as vectors
<
=={{header|Maxima}}==
<
p: new(point)$
Line 1,349 ⟶ 1,538:
q: point(1, 2)$
p@x: 5$</
=={{header|MAXScript}}==
Point is a built-in object type in MAX, so...
<
newPoint = myPoint x:3 y:4</
In practice however, you'd use MAX's built in Point2 type
<
=={{header|MiniScript}}==
<
Point.x = 0
Point.y = 0</
=={{header|Modula-2}}==
<
x, y : INTEGER
END;</
Usage:
<
...
point.x := 12;
point.y := 7;</
=={{header|Modula-3}}==
<
x, y: INTEGER;
END;</
Usage:
Line 1,394 ⟶ 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.
<
options replace format comments java crossref symbols nobinary
Line 1,416 ⟶ 1,605:
res = 'X='getX()',Y='getY()
return res
</syntaxhighlight>
{{out}}
<pre>
Line 1,423 ⟶ 1,612:
=={{header|Nim}}==
<
var p: Point = (12, 13)
var p2: Point = (x: 100, y: 200)</
=={{header|Oberon-2}}==
<
MODULE Point;
TYPE
Line 1,450 ⟶ 1,639:
END Point.
</syntaxhighlight>
=={{header|Objeck}}==
Classes are used for compound data types.
<
class Point {
@x : Int;
Line 1,490 ⟶ 1,679:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
Line 1,497 ⟶ 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.
<
| Leaf of int
| Node of tree * tree
let t1 = Node (Leaf 1, Node (Leaf 2, Leaf 3))</
===Record Type===
<
How to construct a point:
<
You can use the dot (".") to access fields.
<
Fields can be optionally declared to be mutable:
<
Then they can be assigned using the assignment operator "<-"
<
p2.x2 <- 6;
p2 (* evaluates to { x2 = 6; y2 = 5 } *)</
===Tuple Type===
Line 1,526 ⟶ 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:
<
The type of <code>p</code> is a product (indicated by <code>*</code>) of the types of the components:
Line 1,536 ⟶ 1,725:
Using a class :
<
=={{header|ooRexx}}==
ooRexx uses class for compound data types.
<syntaxhighlight lang="oorexx">
p = .point~new(3,4)
say "x =" p~x
Line 1,552 ⟶ 1,741:
::attribute x
::attribute y
</syntaxhighlight>
=={{header|OpenEdge/Progress}}==
Line 1,558 ⟶ 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.
<
field x as int
field y as int
.</
Another option would be a simple class.
=={{header|OxygenBasic}}==
<
'SHORT FORM
type point float x,y
'FULL FORM
type point
Line 1,575 ⟶ 1,764:
float y
end type
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:
<
Now we can access the components by name: P.x and P.y
Often such values are deconstructed by pattern matching:
<
{Show X}
{Show Y}
end</
=={{header|PARI/GP}}==
<
point.y=2;</
=={{header|Pascal}}==
<
x, y: integer;
end;</
=={{header|Perl}}==
===Array===
<
===Hash===
<
x => 3,
y => 8
);</
===Class instance===
<
use strict;
Line 1,617 ⟶ 1,819:
;
my $point = Point->new(x => 3, y => 8);</
=={{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)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span>
<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>
<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>
<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>
<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>
<span style="color: #0000FF;">?</span><span style="color: #000000;">p</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: #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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
point p is {107.5,3.375}
p[x]:107.5, p[y]:3.375
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}}==
<
$point = pack("ii", 1, 2);
Line 1,655 ⟶ 1,887:
list($x,$y) = unpack("ii", $point);
echo $x;
echo $y;</
<
$point = array('x' => 1, 'y' => 2);
Line 1,664 ⟶ 1,896:
# or simply:
echo $point['x'], ' ', $point['y'], "\n";</
<
class Point {
function __construct($x, $y) { $this->x = $x; $this->y = $y; }
Line 1,672 ⟶ 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.</
=={{header|PicoLisp}}==
<
(dm T (X Y)
Line 1,683 ⟶ 1,915:
(setq P (new '(+Point) 3 4))
(show P)</
{{out}}
<pre>$52717735311266 (+Point)
Line 1,690 ⟶ 1,922:
=={{header|Pike}}==
<syntaxhighlight lang="pike">
class Point {
int x, y;
Line 1,705 ⟶ 1,937:
write("%d %d\n", point->x, point->y);
}
</syntaxhighlight>
{{Out}}
<pre>
Line 1,712 ⟶ 1,944:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
define structure
1 point,
Line 1,719 ⟶ 1,951:
</syntaxhighlight>
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">A cartesian point is a record with an x coord and a y coord.</syntaxhighlight>
=={{header|Pop11}}==
<
define :class Point;
slot x = 0;
slot y = 0;
enddefine;</
=={{header|PowerShell}}==
{{works with|PowerShell|5}}
<syntaxhighlight lang="powershell">
class Point {
[Int]$a
Line 1,750 ⟶ 1,985:
$p1.add()
$p2.mul()
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 1,760 ⟶ 1,995:
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
This will create static point that can be called:
<
X = 10,
Y = 20.</
terms can be passed around as values and can have a complex nested structure of any size, eg:
<
=={{header|PureBasic}}==
A basic [http://www.purebasic.com/documentation/reference/structures.html structure] is implemented as;
<
x.i
y.i
EndStructure</
=={{header|Python}}==
The simplest way it to use a tuple, or a list if it should be mutable:
<
p = (3, 4)
p = [3, 4]
print p[X]</
If needed, you can use class:
<
def __init__(self, x=0, y=0):
self.x = x
Line 1,793 ⟶ 2,028:
p = Point()
print p.x</
One could also simply instantiate a generic object and "monkeypatch" it:
<
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</
=== Dictionary ===
Mutable. Can add keys (attributes)
<
Line 1,812 ⟶ 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.
<
>>> help(namedtuple)
Help on function namedtuple in module collections:
Line 1,838 ⟶ 2,073:
Point(x=100, y=22)
>>></
=={{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.
<
# $x
# [1] 3.4
Line 1,861 ⟶ 2,299:
# [1] 1
# $d$f
# [1] TRUE</
=={{header|Racket}}==
Line 1,867 ⟶ 2,305:
The most common method uses structures (similar to records):
<
#lang racket
(struct point (x y))
</syntaxhighlight>
Alternatively, you can define a class:
<
#lang racket
(define point% ; classes are suffixed with % by convention
Line 1,880 ⟶ 2,318:
(super-new)
(init-field x y)))
</syntaxhighlight>
=={{header|Raku}}==
Line 1,887 ⟶ 2,325:
===Array===
<syntaxhighlight lang="raku"
my Int @point = 3, 8; # or constrain to integer elements</
===Hash===
<syntaxhighlight lang="raku"
my Int %point = x => 3, y => 8; # or constrain the hash to have integer values</
===Class instance===
<syntaxhighlight lang="raku"
my Point $point .= new
===[http://design.raku.org/S32/Containers.html#Set Set]===
<syntaxhighlight lang="raku"
my $s2 = set <c d e f>;
say $s1 (&) $s2; # OUTPUT«set(c, e)»
say $s1 ∩ $s2; # we also do Unicode</
=={{header|REXX}}==
<
y= 1.7
point=x y</
:: ---or---
<
y= 1/4e21
Line 1,919 ⟶ 2,357:
bpoint=point
gpoint=5.6 7.3e-12</
=={{header|Ring}}==
<
see new point {x=10 y=20} class point x y
</syntaxhighlight>
Output
<
x: 10.000000
y: 20.000000
</syntaxhighlight>
=={{header|Ruby}}==
<
pt = Point.new(6,7)
puts pt.x #=> 6
Line 1,946 ⟶ 2,384:
pt.each_pair{|member, value| puts "#{member} : #{value}"}
#=> x : 2
#=> y : 5</
=={{header|Rust}}==
Line 1,953 ⟶ 2,391:
====C-like struct====
<
struct Point<T> {
x: T,
Line 1,961 ⟶ 2,399:
let p = Point { x: 1.0, y: 2.5 }; // p is of type Point<f64>
println!("{}, {}", p.x, p.y);
} </
====Tuple struct====
These are basically just named tuples.
<
fn main() {
let p = Point(1.0, 2.5);
println!("{},{}", p.0, p.1);
}</
===Tuples===
<
let p = (0.0, 2.4);
println!("{},{}", p.0, p.1);
}</
=={{header|Scala}}==
<
val p = Point(1, 2)
println(p.y) //=> 2</
=={{header|Scheme}}==
Using [http://srfi.schemers.org/srfi-9/srfi-9.html SRFI 9]:
<
(make-point x y)
point?
(x point-x)
(y point-y))</
=={{header|Seed7}}==
<
var integer: x is 0;
var integer: y is 0;
end struct;</
=={{header|Shen}}==
<
X : number; Y : number;
====================
[point X Y] : point;)</
Pairs (distinct from cons cells) are also supported, in which case a point would be denoted by (number * number):
<
(@p 1 2) : (number * number)</
=={{header|Sidef}}==
<
var point = Point(1, 2);
say point.y; #=> 2</
=={{header|SIMPOL}}==
The <code>point</code> type is pre-defined in [SIMPOL], so we will call this mypoint.
<
embed
integer x
integer y
end type</
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 2,023 ⟶ 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.
<
embed
integer x
Line 2,032 ⟶ 2,470:
me.x = x
me.y = y
end function me</
=={{header|SNOBOL4}}==
<
p1 = point(10,20)
p2 = point(10,40)
output = "Point 1 (" x(p1) "," y(p1) ")"
output = "Point 2 (" x(p2) "," y(p2) ")"
end</
=={{header|Standard ML}}==
Line 2,048 ⟶ 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.
<
| Leaf of int
| Node of tree * tree
val t1 = Node (Leaf 1, Node (Leaf 2, Leaf 3))</
===Tuple Type===
Line 2,058 ⟶ 2,496:
You can make a tuple literal by using a comma-delimited list surrounded by parentheses, without needing to declare the type first:
<
The type of <code>p</code> is a product (indicated by <code>*</code>) of the types of the components:
Line 2,075 ⟶ 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:
<
The type of <code>p</code> is a comma-delimited list of <code>key:type</code> pairs of the types of the fields:
Line 2,089 ⟶ 2,527:
See '''[https://www.stata.com/help.cgi?m2_struct struct]''' in Stata help.
<
struct Point {
real scalar x, y
Line 2,104 ⟶ 2,542:
test()
30
end</
=={{header|Swift}}==
<
struct Point {
var x:Int
Line 2,125 ⟶ 2,563:
self.y = y
}
}</
=={{header|Tcl}}==
This can be done using an associative array:
<
set point(y) 7
puts "Point is {$point(x),$point(y)}"
# => Point is {4,7}</
Or a dictionary:
{{works with|Tcl|8.5}}
<
dict set point y 7
puts "Point is {[dict get $point x],[dict get $point y]}"</
Or an object:
{{works with|Tcl|8.6}}
<
variable x y
constructor {X Y} {set x $X;set y $Y}
Line 2,149 ⟶ 2,587:
Point create point 4 5
point y 7
puts "Point is [point show]"</
=={{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 2,159 ⟶ 2,629:
In TXR Lisp, a structure type can be created:
<
If it is okay for the coordinates to be initialized to <tt>nil</tt>, it can be condensed to:
<
The <tt>nil</tt> denotes that a <tt>point</tt> has no supertype: it doesn't inherit from anything.
Line 2,169 ⟶ 2,639:
This structure type can then be instantiated using the <tt>new</tt> macro (not the only way):
<
(new point x 1) ;; -> #S(point x 1 y 0)
(new point x 1 y 1) ;; -> #S(point x 1 y 1)</
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:
<
The existing construction methods continue to work, but in addition, this is now possible:
<
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:
<
(inc p.x delta.x)
(inc p.y delta.y))</
=={{header|UNIX Shell}}==
{{works with|ksh93}}
ksh93 allows you to define new compound types with the <tt>typeset -T</tt> command.
<
typeset x
typeset y
Line 2,200 ⟶ 2,670:
echo ${p.x} ${p.y}
Point q=(x=3 y=4)
echo ${q.x} ${q.y}</
{{out}}
<pre>( x=1 y=2 )
Line 2,207 ⟶ 2,677:
You can also declare compound variables "on the fly" without using a defined type:
<
point.x=5
point.y=6
echo $point
echo ${point.x} ${point.y}</
{{out}}
<pre>( x=5 y=6 )
Line 2,218 ⟶ 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
A constant instance of the record can be declared like this.
<
A function returning a value of this type can be defined like this,
<
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.
<
u = ~y p</
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}}==
<
int x;
int y;
}</
=={{header|VBA}}==
<
x As Integer
y As Integer
End Type</
=={{header|Vim Script}}==
One cannot create new data types in Vim Script. A point could be represented by a dictionary:
<
return {"x": a:x, "y": a:y}
endfunction
Line 2,254 ⟶ 2,724:
echon "Point 1: x = " p1.x ", y = " p1.y "\n"
echon "Point 2: x = " p2.x ", y = " p2.y "\n"</
{{Out}}
Line 2,265 ⟶ 2,735:
A simple structure with two public, mutable fields:
<
Public X, Y As Integer
End Structure</
=== Immutable Structures ===
Line 2,279 ⟶ 2,749:
Below is the same <code>Point</code> as above, except with an immutable API.
<
ReadOnly Property X As Integer
ReadOnly Property Y As Integer
Line 2,287 ⟶ 2,757:
Me.Y = y
End Sub
End Structure</
=={{header|V (Vlang)}}==
Vlang also supports embedding structs into other structs and assigning methods to structs.
<syntaxhighlight lang="v (vlang)">struct Point {
x int
y int
}
// main() declaration can be skipped in one file programs
// we can define whether immutable or mutable by using the "mut" keyword
mut p := Point{
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 2,294 ⟶ 2,836:
===Attributes===
Attributes are often used for simple values. This is how a point might be represented in SVG, for example.
<
<!-- 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></
===Children===
More complex, multivariate, and nested data structures can be represented using child nodes.
<
<point>
<x>20</x>
Line 2,309 ⟶ 2,851:
</circle>
<!-- context is a circle node. Children are accessed using a path-like notation (hence the name "XPath"). --></
<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:
<
fcn init(x,y){self.x=x.toFloat(); self.y=y.toFloat(); }
fcn toString{ "P(%f,%f)".fmt(x,y) }
Line 2,320 ⟶ 2,881:
//... __opEQ == etc
}
Point(1,2).println() //-->P(1.000000,2.000000)</
which can be pretty heavy weight. [read only] lists can work just as well:
<
{{omit from|bc}}
Line 2,328 ⟶ 2,889:
=={{header|zonnon}}==
<
{ref,public} (* class *)
Point = object(ord,abs: integer)
Line 2,352 ⟶ 2,913:
self.y := abs;
end Point;
</syntaxhighlight>
|