Compound data type: Difference between revisions

→‎{{header|Phix}}: added class-based alternative
No edit summary
(→‎{{header|Phix}}: added class-based alternative)
Line 1,658:
 
=={{header|Phix}}==
===traditional sequence===
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.
<lang Phix>enum x,y
Line 1,665 ⟶ 1,666:
 
point p = {175,3.375}
 
p[x] -= p[y]*20
 
puts(1,"point p is ")
?p
printf(1,"p[x]:%g, p[y]:%g\n",{p[x],p[y]})
 
p[x] = 0 -- fine
p[y] = "string" -- run-time error</lang>
Line 1,678 ⟶ 1,676:
point p is {107.5,3.375}
p[x]:107.5, p[y]:3.375
 
C:\Program Files (x86)\Phix\test.exw:1512
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
<lang Phix>class point
public atom x,y
end class
point p = new({175,3.375})
p.x -= p.y*20
printf(1,"p.x:%g, p.y:%g\n",{p.x,p.y})
p.x = 0 -- fine
p.y = "string" -- run-time error</lang>
{{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>
 
7,805

edits