Methods in PureScript

Our first example demonstrates how to define methods on struct types in PureScript.

module Main where

import Prelude
import Effect (Effect)
import Effect.Console (log)

-- Define a record type similar to a struct
type Rect = { width :: Int, height :: Int }

-- Define a function to create a new Rect
newRect :: Int -> Int -> Rect
newRect w h = { width: w, height: h }

-- Define an area method for Rect
area :: Rect -> Int
area r = r.width * r.height

-- Define a perim method for Rect
perim :: Rect -> Int
perim r = 2 * r.width + 2 * r.height

main :: Effect Unit
main = do
  let r = newRect 10 5

  -- Call the methods defined for our record
  log $ "area: " <> show (area r)
  log $ "perim: " <> show (perim r)

  -- In PureScript, we don't need to worry about pointer vs value semantics
  -- as it's a purely functional language. The following calls are equivalent:
  log $ "area: " <> show (area r)
  log $ "perim: " <> show (perim r)

In PureScript, we use records instead of structs. Methods are defined as separate functions that take the record as their first argument.

PureScript is a purely functional language, so we don’t have the concept of pointer receivers or value receivers. Instead, functions always operate on immutable data.

To run this program, you would typically compile it to JavaScript and then run it with Node.js:

$ pulp run
area: 50
perim: 30
area: 50
perim: 30

Next, we’ll explore PureScript’s type classes, which provide a way to define interfaces for polymorphic functions.