examples/gallery/01-points.hero
Come creare record e chiamare una funzione con la sintassi di un metodo.
- 49 righe
Un record raggruppa campi con un nome. Per costruirlo, devi indicare il nome di ogni campo: Point(3, 4) non è valido. I nomi distinguono gli argomenti anche quando hanno lo stesso tipo.
Eseguilo
Questo esempio serve a illustrare il linguaggio. Qui trovi il programma e non un risultato: non ci sono ancora test che confrontino il suo output byte per byte.
Il programma
## Points
#
# Records, their constructors, and UFCS. Every field is named at the call
# site, always — `Point(3, 4)` does not exist.
# A position on the integer grid.
record Point
x: i64
y: i64
# A rectangle, by two corners.
record Rect
corner: Point
extent: Point
# Squared distance. Avoids the square root to keep it exact.
#
# Both parameters are `Point`, so §4.9 makes the names mandatory at every call
# site: `a.dist2(b: c)` cannot be silently the other way round. That is the rule
# that spends tokens exactly where argument inversion happens.
function dist2(a: Point, b: Point) -> i64
dx = a.x - b.x
dy = a.y - b.y
return dx * dx + dy * dy
# The point halfway between two others, rounded towards zero.
function midpoint(a: Point, b: Point) -> Point
return Point(x: (a.x + b.x) / 2, y: (a.y + b.y) / 2)
function area(r: Rect) -> i64
return r.extent.x * r.extent.y
# Reads as a sentence, and it is one function call: `translate(r, by)`.
function translate(r: Rect, by: Point) -> Rect
moved = Point(x: r.corner.x + by.x, y: r.corner.y + by.y)
return Rect(corner: moved, extent: r.extent)
test "the 3-4-5 triangle"
assert dist2(a: Point(x: 0, y: 0), b: Point(x: 3, y: 4)) == 25
test "a rectangle keeps its size when it moves"
unit = Rect(corner: Point(x: 0, y: 0), extent: Point(x: 2, y: 3))
assert unit.translate(Point(x: 10, y: 10)).area() == unit.area()
function main()
a = Point(x: 0, y: 0)
b = Point(x: 3, y: 4)
print("distance squared: ", a.dist2(b: b))
print("midpoint x: ", a.midpoint(b: b).x)
impronta sha256 f566285ac427 · 1 file · index.json
Successivo: 02-tokens. Tutti gli esempi. ← Precedente: 00-first
Eseguine uno: i quattro comandi. Impara il linguaggio, oppure leggi la specifica completa in un solo file.