PureScript Records - A comprehensive Guide

by|inArticles||2 min read
PureScript Records<br>
PureScript Records<br>

PureScript is a functional programming language that is closely related to Haskell. One of the key features of PureScript is its support for records, which are similar to objects in object-oriented languages like Java or C#. In this guide, we will take a look at how to use records in PureScript.

Records in PureScript are essentially a collection of key-value pairs, where the keys are strings and the values can be of any type.

Define a Record in PureScript

To define a record, we use the record keyword followed by a list of field names and their corresponding types. For example, here is how we might define a record to represent a car:

type Car =
  { color :: String
  , year :: Int
  }

This defines a new type called Car, which has two fields: color and year. We can create a new instance of this type by using the {} notation, like this: 

let myCar = { color: "Blue", year: 2008 }

We can also use the . notation to access the fields of a record:

traceM myCar.color // Output: "Blue"
tranceM myCar.year   // Output: 2008

Note: We are using the traceM function to log to console. This is a monadic function which is usually used in expressions with a do notation. There are other ways to log to console as well. If you are interested, I have written about it in detail here: How to log to Console in PureScript

PureScript Records and Pattern Matching

Records also support pattern matching, which allows us to extract the values of the fields of a PureScript record and bind them to variables. For example, we can use the following code to extract the color and year of a car:

let getColorAndYearTuple car =
  case car of
    { color, year } -> (color, year)

In this example, the case statement matches the input car against the pattern { color, year }, which binds the color and year fields to the variables color and year, respectively. 

Records in PureScript are a powerful feature that allows us to work with data in a structured and meaningful way. They are similar to objects in other languages, but with the added benefits of type safety and pattern matching. With this knowledge, you should now be able to use records in your PureScript projects with confidence.

Thank you for reading this far! Let’s connect. You can @ me on X (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

Related Articles

© Copyright 2024 - ersocon.net - All rights reservedVer. 415