Record Types

I am working on adding record types to Newton. Lets look at the syntax first, then discuss how they relate to algebraic data types and classes.

Syntax

# This defines a new data type Point with fields x and y, both of type Float
record Point(x: Float, y: Float)

# Instances are created using function call syntax
let origin = Point(0.0, 0.0)

# Access fields using dot notation
print(origin.x)

# Field types can be omitted, making them polymorphic
record Pair(first, second)

# Introduce type variables using square brackets
record Point2[T](x: T, y: T)
record Point3[T](x: T, y: T, z: T)

Compared to Algebraic Data Types

The main difference between algebraic data types (ADTs) and records is that ADTs have variants while records do not. The fields of an ADT can only be accessed by first checking what variant it is, while a record is just a grouping of fields that can be accessed directly using dot notation. For ADTs we need to prevent direct access and require the use of pattern matching instead.

In summary:

  • Record fields can be accessed directly using dot expressions, without having to pattern match first.
  • Each record type is a type in its own right and not merely a case in a sum type.
  • Record fields must have names but the types can be omitted.
  • ADT fields must have types but do not need to be named.

Otherwise they work the same.

Compared to Classes

I have not started on classes yet but to meet people’s expectations they probably need to be mutable reference types, and records in contrast will be immutable value types.

Records in Newton are different from classes in that they:

  • Are immutable.
  • Are stored inline when contained in another object.
  • Are not organized in a hierarchy.
  • Can only have public fields.

But why have both records and classes?

We could support both behaviors in a single kind of type using field attributes such as mut, const and public but I think having two separate but clearly defined concepts will be better. With this design you know that a record is immutable always and everywhere and in whole.

Stefan