Chapter 4 Definitions

Table of Contents
Overview
Definitions

Overview

Definitions declare new types that can be used throughout a program. Types can have properties, methods, and nested definitions.

Definitions

Definitions declare new types that can be used throughout a program.

Structure Definitions

The define keyword creates a new structure type with named properties.

InputResult
define Point(x: int, y: int)
Point(3, 4)
{"_type":"Point","x":3,"y":4}
define Point(x: int, y: int)
Point(3, 4).x
3
define Point(x: int, y: int)
let p Point(3, 4)
p.x + p.y
7
define Point(x: int, y: int)
define Rectangle(origin: Point, width: int, height: int)
Rectangle(Point(0, 0), 10, 5).width
10

Union Definitions

Unions define types with multiple variants. Each variant can optionally carry a value.

InputResult
define Option union(Some: int, None)
Some(5)
{"_type":"Option","_variant":"Some","value":5}
define Option union(Some: int, None)
None
{"_type":"Option","_variant":"None"}
define Result union(Ok: int, Err: String)
Ok(42)
{"_type":"Result","_variant":"Ok","value":42}
define Result union(Ok: int, Err: String)
Err("error")
{"_type":"Result","_variant":"Err","value":"error"}
define Option union(Some: int, None)
Some(5).value
5