Title here
Summary here
Our structs.ps
example demonstrates how to work with records in the PureScript programming language.
PureScript’s Record
types are type-safe collections of fields, which are useful for grouping data together to form records. Here’s the full source code in PureScript:
module Main where
import Prelude
import Effect.Console (log)
import Effect (Effect)
-- This `Person` type has `name` and `age` fields.
type Person =
{ name :: String
, age :: Int
}
-- `newPerson` constructs a new person record with the given name.
newPerson :: String -> Person
newPerson name =
{ name: name
, age: 42
}
main :: Effect Unit
main = do
-- This syntax creates a new record.
log $ show { name: "Bob", age: 20 }
-- You can name the fields when initializing a record.
log $ show { name: "Alice", age: 30 }
-- Omitted fields will result in type errors, so all fields must be provided.
log $ show { name: "Fred", age: 0 }
-- Here's how to create a pointer to a record. This isn't directly required in PureScript.
let ann = { name: "Ann", age: 40 }
log $ show ann
-- It's idiomatic to encapsulate new record creation in constructor functions.
log $ show (newPerson "Jon")
-- Access record fields with a dot.
let sean = { name: "Sean", age: 50 }
log $ show sean.name
-- You can also modify records using record updates.
let updatedAge = sean { age = 51 }
log $ show updatedAge.age
-- If a record type is only used for a single value, we don’t
-- have to name it. Here’s an anonymous record.
let dog = { name: "Rex", isGood: true }
log $ show dog
When running this PureScript program, you will see the following output:
$ spago run
Record { name: "Bob", age: 20 }
Record { name: "Alice", age: 30 }
Record { name: "Fred", age: 0 }
Record { name: "Ann", age: 40 }
Record { name: "Jon", age: 42 }
"Sean"
50
51
Record { name: "Rex", isGood: true }
Now that you can work with records in PureScript, let’s learn more about the language.