Maps in PureScript

Our first program will explore the usage of maps, which are key-value data structures. Here’s the full source code translated into PureScript.

module Main where

import Prelude
import Data.Map as Map
import Effect (Effect)
import Effect.Class.Console (log)

main :: Effect Unit
main = do
    -- Create an empty map
    let m = Map.empty :: Map String Int

    -- Set key/value pairs
    let m1 = Map.insert "k1" 7 m
    let m2 = Map.insert "k2" 13 m1

    -- Print the map
    log $ "map: " <> show m2

    -- Get value for a key
    let v1 = Map.lookup "k1" m2
    log $ "v1: " <> show v1

    -- Get value for a non-existent key (returns Nothing)
    let v3 = Map.lookup "k3" m2
    log $ "v3: " <> show v3

    -- Get the size of the map
    log $ "len: " <> show (Map.size m2)

    -- Delete a key/value pair
    let m3 = Map.delete "k2" m2
    log $ "map: " <> show m3

    -- Clear the map (keep as empty)
    let m4 = Map.empty
    log $ "map: " <> show m4

    -- Check if a key is present
    let isKeyPresent = Map.member "k2" m2
    log $ "prs: " <> show isKeyPresent

    -- Declare and initialize a new map
    let n = Map.fromFoldable [("foo", 1), ("bar", 2)] :: Map String Int
    log $ "map: " <> show n

    -- Utility function to compare maps
    let n2 = Map.fromFoldable [("foo", 1), ("bar", 2)] :: Map String Int
    if n == n2 then log "n == n2" else pure unit

Explanation

  • Creating an Empty Map: We use Map.empty to create an empty map of type Map String Int.
  • Setting Key/Value Pairs: Use Map.insert to add key-value pairs to the map.
  • Printing a Map: log and show are used to print the map in a readable format.
  • Getting a Value: Map.lookup is used to retrieve the value associated with a particular key.
  • Handling Non-existent Keys: If a key doesn’t exist, Map.lookup returns Nothing.
  • Getting the Size of the Map: Use Map.size to obtain the number of key-value pairs.
  • Deleting a Key/Value Pair: The Map.delete function removes a specified key from the map.
  • Clearing the Map: Set the map to Map.empty to clear all key-value pairs.
  • Checking Key Presence: Use Map.member to check if a key exists in the map.
  • Declaring and Initializing a Map: Map.fromFoldable initializes a new map with given key-value pairs.
  • Comparing Maps: Directly compare two maps to check for equality and log the result.

Now that we have explored map functionalities, let’s dive deeper into other aspects of PureScript.