examples/gallery/01-points.hero
Define records, create values and call functions with method syntax.
- 49 lines
A record groups named fields into one value. Creating one requires you to name every field: Point(3, 4) does not compile. The names make it clear which value belongs to which field, even when the fields have the same type.
Run it
These files introduce the language one feature at a time. This page shows the program and not a result, because no test compares their output byte for byte yet.
The program
## 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)
fingerprint sha256 f566285ac427 · 1 file · index.json
Next: 02-tokens. All the examples. ← Previous: 00-first
Run one yourself: the four commands. Learn the language, or read the full specification in one file.