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:
Defining a Record Type: The
personrecord type is defined withnameandagefields.type person = { name : string, age : int }Constructing a Record:
newPersonconstructs a newpersonrecord with a givennameand assignsageto 42.fun newPerson (name : string) = let val p = { name = name, age = 42 } in p endRecord Instances: Different instances of the
personrecord 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"Accessing Fields: Access fields within a record using the
#operator.val sean = { name = "Sean", age = 50 } val seanName = #name seanReference 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.ageAnonymous 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.