Pointers in PureScript

module Main where

import Prelude
import Effect (Effect)
import Effect.Console (log)
import Data.Maybe (Maybe(..))
import Data.Int as Int

-- We'll show how references work in contrast to values with
-- 2 functions: `zeroval` and `zeroptr`. `zeroval` has an
-- Int parameter, so arguments will be passed to it by
-- value. `zeroval` will get a copy of `ival` distinct
-- from the one in the calling function.
zeroval :: Int -> Effect Unit
zeroval ival = do
  let _ = 0
  pure unit

-- `zeroptr` in contrast has a `Maybe Int` parameter, which we'll use to simulate
-- a pointer. If the `Maybe Int` is `Just`, we'll modify its value.
-- This is the closest we can get to pointer behavior in PureScript.
zeroptr :: Maybe Int -> Maybe Int
zeroptr mval = case mval of
  Just _ -> Just 0
  Nothing -> Nothing

main :: Effect Unit
main = do
  let i = 1
  log $ "initial: " <> show i

  zeroval i
  log $ "zeroval: " <> show i

  -- In PureScript, we don't have direct pointers, so we'll use Maybe Int
  -- to simulate the pointer behavior
  case zeroptr (Just i) of
    Just newI -> do
      log $ "zeroptr: " <> show newI
    Nothing -> 
      log "zeroptr: No value"

  -- In PureScript, we don't have a direct equivalent to printing memory addresses
  -- Instead, we'll print a placeholder message
  log "pointer: (Memory addresses not directly accessible in PureScript)"

PureScript, being a purely functional language, doesn’t have pointers in the same way that languages like C or Go do. Instead, we use other constructs to achieve similar behavior. In this example, we’ve used Maybe Int to simulate pointer-like behavior.

The zeroval function in PureScript doesn’t actually modify its parameter, as PureScript functions are pure and don’t have side effects. The zeroptr function returns a new Maybe Int instead of modifying an existing value.

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

$ pulp build
$ node output/Main.js
initial: 1
zeroval: 1
zeroptr: 0
pointer: (Memory addresses not directly accessible in PureScript)

Note that the output is slightly different from the original Go program. The zeroval function doesn’t actually modify the value (as PureScript functions are pure), and we can’t directly access or print memory addresses in PureScript.

This example demonstrates how PureScript handles values and references differently from languages with mutable state and pointers. In PureScript, we focus on transforming data rather than modifying it in place.