Structs in Standard ML

Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

This person record type has name and age fields.

In Standard ML:

type person = { name : string, age : int }

fun newPerson (name : string) = 
    let val p = { name = name, age = 42 }
    in p end

val bob = { name = "Bob", age = 20 }

val alice = { name = "Alice", age = 30 }

val fred = { name = "Fred", age = 0 }

val ann = { name = "Ann", age = 40 }

val jon = newPerson "Jon"

val sean = { name = "Sean", age = 50 }
val seanName = #name sean

val sp = ref sean 
val spAge = !sp.age

val _ = sp := { !sp with age = 51 } 
val spNewAge = !sp.age

val dog = { name = "Rex", isGood = true }

Explanation:

  1. Defining a Record Type: The person record type is defined with name and age fields.

    type person = { name : string, age : int }
  2. Constructing a Record: newPerson constructs a new person record with a given name and assigns age to 42.

    fun newPerson (name : string) = 
        let val p = { name = name, age = 42 }
        in p end
  3. Record Instances: Different instances of the person record are created.

    val bob = { name = "Bob", age = 20 }
    val alice = { name = "Alice", age = 30 }
    val fred = { name = "Fred", age = 0 }
    val ann = { name = "Ann", age = 40 }
    val jon = newPerson "Jon"
  4. Accessing Fields: Access fields within a record using the # operator.

    val sean = { name = "Sean", age = 50 }
    val seanName = #name sean
  5. Reference to Record and Mutability: Create a mutable reference to a record and modify its fields.

    val sp = ref sean 
    val spAge = !sp.age
    
    val _ = sp := { !sp with age = 51 }
    val spNewAge = !sp.age
  6. Anonymous Record: Create an instance of an anonymous record type.

    val dog = { name = "Rex", isGood = true }

This example showcases how to use records in Standard ML to group data and manage mutable references. Moving forward, we can explore further language features and idiomatic usage.