Compound data type: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
Puppydrum64 (talk | contribs) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(16 intermediate revisions by 13 users not shown) | |||
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 47:
NESASM3 syntax:
<
.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</
VASM syntax:
<
point_ram equ $0400
point_x equ point_ram
point_y equ point_ram+MAX_POINT_OBJECTS</
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:
<
point_ram equ $0400
point_x equ point_ram
point_y equ point_ram+MAX_POINT_OBJECTS
LDX #3
Line 71:
STA $00
LDA point_y,x
STA $01</
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<
DEFINE REALPTR="CARD"
Line 101:
PrintR(p2.rx) Print(",")
PrintR(p2.ry) Print(")")
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Compound_data_type.png Screenshot from Atari 8-bit computer]
Line 110:
=={{header|ActionScript}}==
<
{
public class Point
Line 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 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 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 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 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 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 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 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 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 375:
iMagicNumber: .int 0xCCCCCCCD
</syntaxhighlight>
=={{header|Arturo}}==
<
x: 10
y: 20
]
print point</
{{out}}
Line 394:
There are numerous ways to do this. The simplest is to use an "unboxed" tuple type:
<
val p : point double = (1.0, 3.0)</
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:
<
| Point of (t, t)
val p : point double = Point (1.0, 3.0)</
=={{header|AutoHotkey}}==
Line 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 424:
for (i in p) print( i, ":", p[i] )
}</
{{out}}
<pre>
Line 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 449:
{{works with|PowerBASIC}}
<
x AS INTEGER
y AS INTEGER
END TYPE</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
=={{header|Bracmat}}==
Line 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 473:
& 7:?(pt..x)
& out$(!(pt..x) !(pt..y))
);</
{{out}}
<pre>3 4
Line 486:
=={{header|C}}==
<
{
int x;
int y;
} Point;</
=={{header|C sharp|C#}}==
<
{
public int x, y;
Line 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 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}}==
Line 550:
Aside from this, they work the same way.
<
point = struct[x, y: int]
mutable_point = record[x, y: int]
Line 556:
% Initialization
p: point := point${x: 10, y: 20}
mp: mutable_point := mutable_point${x: 10, y: 20}</
The fields can be accessed using the <code>.</code> syntax:
<
bar := p.y</
''Record''s, but not ''struct''s, allow updating the fields in the same way.
<
mp.y := 40</
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:
<
bar := point$get_y(p)</
<
mutable_point$set_y(mp, 40)</
=={{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 603 ⟶ 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 621 ⟶ 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].
<
getter x : T
getter y : T
Line 633 ⟶ 635:
end
puts Point(Int32).new 13, 12 #=> Point(Int32)(@x=13, @y=12)</
=={{header|D}}==
<
// A normal POD struct
// (if it's nested and it's not static then it has a hidden
Line 682 ⟶ 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 701 ⟶ 715:
}
return point
}</
=={{header|EchoLisp}}==
<
(lib 'struct)
(struct Point (x y))
Line 717 ⟶ 731:
(Point 3 'albert)
❌ error: #number? : type-check failure : albert → 'Point:y'
</syntaxhighlight>
=={{header|Ela}}==
Line 723 ⟶ 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 744 ⟶ 759:
Y := y
}
}</
=={{header|Elixir}}==
<
...(1)> defstruct x: 0, y: 0
...(1)> end
Line 764 ⟶ 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 795 ⟶ 810:
--Each time a new record is generated
--END
</syntaxhighlight>
=={{header|Erlang}}==
<
-module(records_test).
-compile(export_all).
Line 809 ⟶ 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 825 ⟶ 840:
printf(1,"x = %d, y = %3.3f\n",point)
printf(1,"x = %s, y = %3.3f\n",point)
</syntaxhighlight>
{{out}}
<pre>
Line 835 ⟶ 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 841 ⟶ 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 869 ⟶ 884:
}
}
</syntaxhighlight>
{{out}}
Line 880 ⟶ 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 886 ⟶ 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 919 ⟶ 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 932 ⟶ 947:
Print p.x, p.y
Print p2.x, p2.y
Sleep</
{{out}}
Line 939 ⟶ 954:
3 4
</pre>
=={{header|FutureBasic}}==
<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}}==
<
x, y float64
}
</syntaxhighlight>
=={{header|Groovy}}==
===Declaration===
<
int x
int y
Line 956 ⟶ 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 976 ⟶ 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 998 ⟶ 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 1,032 ⟶ 1,061:
Point p9 = [y:-2]
assert 0 == p9.x
assert -2 == p9.y</
=={{header|Haskell}}==
Line 1,072 ⟶ 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 1,087 ⟶ 1,116:
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang
=={{header|IDL}}==
<
point.y = 7
print, point
;=> { 6 7}</
=={{header|J}}==
Line 1,100 ⟶ 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'
Line 1,116 ⟶ 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,133 ⟶ 1,186:
System.out.println("y = " + point.y );
}
}</
=={{header|JavaScript}}==
<
var point = {x : 1, y : 2};
Line 1,154 ⟶ 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,166 ⟶ 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,190 ⟶ 1,243:
@show a + b + c
@show a == b
@show a + a == c</
{{out}}
Line 1,204 ⟶ 1,257:
=={{header|KonsolScript}}==
<
Point,
Number x,
Number y
)</
Instanciate it with...
<
Var:Point point;
}</
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,224 ⟶ 1,277:
p.y = 4
println(p)
}</
{{out}}
Line 1,233 ⟶ 1,286:
=={{header|Lambdatalk}}==
<
1) a pair
{def P {P.new 1 2}}
Line 1,257 ⟶ 1,310:
{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,274 ⟶ 1,335:
local(point) = Point(33, 42)
#point->x
#point->y</
{{out}}
Line 1,284 ⟶ 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,330 ⟶ 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,337 ⟶ 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,363 ⟶ 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,372 ⟶ 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,387 ⟶ 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,401 ⟶ 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,420 ⟶ 1,481:
end--if type(op1)
end--cPoint.__sub
</syntaxhighlight>
Usage example:
<
a = newPoint(1, 2)
b = newPoint(3, 4)
Line 1,432 ⟶ 1,493:
print(c:getXY()) --> 4 6
print((a-b):getXY()) --> -2 -2 -- using __sub behaviour
</syntaxhighlight>
=={{header|Maple}}==
<
Point:-x;
Point:-y;</
{{out}}
<pre>
Line 1,447 ⟶ 1,508:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Expressions like point[x, y] can be used without defining.
<
Out[1]= point[2, 3]
Line 1,457 ⟶ 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,477 ⟶ 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,522 ⟶ 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,544 ⟶ 1,605:
res = 'X='getX()',Y='getY()
return res
</syntaxhighlight>
{{out}}
<pre>
Line 1,551 ⟶ 1,612:
=={{header|Nim}}==
<
var p: Point = (12, 13)
var p2: Point = (x: 100, y: 200)</
=={{header|Oberon-2}}==
<
MODULE Point;
TYPE
Line 1,578 ⟶ 1,639:
END Point.
</syntaxhighlight>
=={{header|Objeck}}==
Classes are used for compound data types.
<
class Point {
@x : Int;
Line 1,618 ⟶ 1,679:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
Line 1,625 ⟶ 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,654 ⟶ 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,664 ⟶ 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,680 ⟶ 1,741:
::attribute x
::attribute y
</syntaxhighlight>
=={{header|OpenEdge/Progress}}==
Line 1,686 ⟶ 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
Line 1,716 ⟶ 1,777:
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,758 ⟶ 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.
<!--<
<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>
Line 1,777 ⟶ 1,838:
<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>
<!--</
{{out}}
<pre>
Line 1,793 ⟶ 1,854:
{{libheader|Phix/Class}}
You could also use a class (not pwa/p2js)
<!--<
<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>
Line 1,803 ⟶ 1,864:
<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>
<!--</
{{out}}
<pre>
Line 1,817 ⟶ 1,878:
=={{header|PHP}}==
<
$point = pack("ii", 1, 2);
Line 1,826 ⟶ 1,887:
list($x,$y) = unpack("ii", $point);
echo $x;
echo $y;</
<
$point = array('x' => 1, 'y' => 2);
Line 1,835 ⟶ 1,896:
# or simply:
echo $point['x'], ' ', $point['y'], "\n";</
<
class Point {
function __construct($x, $y) { $this->x = $x; $this->y = $y; }
Line 1,843 ⟶ 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,854 ⟶ 1,915:
(setq P (new '(+Point) 3 4))
(show P)</
{{out}}
<pre>$52717735311266 (+Point)
Line 1,861 ⟶ 1,922:
=={{header|Pike}}==
<syntaxhighlight lang="pike">
class Point {
int x, y;
Line 1,876 ⟶ 1,937:
write("%d %d\n", point->x, point->y);
}
</syntaxhighlight>
{{Out}}
<pre>
Line 1,883 ⟶ 1,944:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
define structure
1 point,
Line 1,890 ⟶ 1,951:
</syntaxhighlight>
=={{header|Plain English}}==
<
=={{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,924 ⟶ 1,985:
$p1.add()
$p2.mul()
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 1,934 ⟶ 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,967 ⟶ 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,986 ⟶ 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 2,012 ⟶ 2,073:
Point(x=100, y=22)
>>></
=={{header|QB64}}==
<
x As Double
y As Double
Line 2,024 ⟶ 2,085:
p.y = 2.412
Print p.x; p.y</
{{out}}
<pre> 15.42 2.412</pre>
Line 2,038 ⟶ 2,099:
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 ( --> [ )
Line 2,048 ⟶ 2,109:
dup x peek echo cr
99 swap y poke
y peek echo cr</
{{out}}
Line 2,059 ⟶ 2,120:
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.
<
item.0
{ item.1.0
Line 2,071 ⟶ 2,132:
} item.1
item.2
}struct mystruct</
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.)
Line 2,079 ⟶ 2,140:
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>
<
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}}
Line 2,094 ⟶ 2,155:
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
Line 2,201 ⟶ 2,262:
{}.name again ]
{}.struct release
{}.path release ] builds struct{ ( [ $ --> [ $ )</
Finally we use <code>struct{</code> etc. to fulfil the requirements go the task.
<
point
dup x {peek} echo cr
99 swap y {poke}
y {peek} echo cr</
{{out}}
Line 2,219 ⟶ 2,280:
=={{header|R}}==
R uses the list data type for compound data.
<
# $x
# [1] 3.4
Line 2,238 ⟶ 2,299:
# [1] 1
# $d$f
# [1] TRUE</
=={{header|Racket}}==
Line 2,244 ⟶ 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 2,257 ⟶ 2,318:
(super-new)
(init-field x y)))
</syntaxhighlight>
=={{header|Raku}}==
Line 2,264 ⟶ 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 2,296 ⟶ 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 2,323 ⟶ 2,384:
pt.each_pair{|member, value| puts "#{member} : #{value}"}
#=> x : 2
#=> y : 5</
=={{header|Rust}}==
Line 2,330 ⟶ 2,391:
====C-like struct====
<
struct Point<T> {
x: T,
Line 2,338 ⟶ 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,400 ⟶ 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,409 ⟶ 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,425 ⟶ 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,435 ⟶ 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,452 ⟶ 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,466 ⟶ 2,527:
See '''[https://www.stata.com/help.cgi?m2_struct struct]''' in Stata help.
<
struct Point {
real scalar x, y
Line 2,481 ⟶ 2,542:
test()
30
end</
=={{header|Swift}}==
<
struct Point {
var x:Int
Line 2,502 ⟶ 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,526 ⟶ 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,536 ⟶ 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,546 ⟶ 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,577 ⟶ 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,584 ⟶ 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,595 ⟶ 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,631 ⟶ 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,642 ⟶ 2,735:
A simple structure with two public, mutable fields:
<
Public X, Y As Integer
End Structure</
=== Immutable Structures ===
Line 2,656 ⟶ 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,664 ⟶ 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}}==
<
construct new(x, y) {
_x = x
Line 2,689 ⟶ 2,823:
p.y = 3
// print without using the toString method
System.printAll(["(", p.x, ", ", p.y, ")"])</
{{out}}
Line 2,702 ⟶ 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,717 ⟶ 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,728 ⟶ 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,736 ⟶ 2,889:
=={{header|zonnon}}==
<
{ref,public} (* class *)
Point = object(ord,abs: integer)
Line 2,760 ⟶ 2,913:
self.y := abs;
end Point;
</syntaxhighlight>
|