Title here
Summary here
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
Map.empty
to create an empty map of type Map String Int
.Map.insert
to add key-value pairs to the map.log
and show
are used to print the map in a readable format.Map.lookup
is used to retrieve the value associated with a particular key.Map.lookup
returns Nothing
.Map.size
to obtain the number of key-value pairs.Map.delete
function removes a specified key from the map.Map.empty
to clear all key-value pairs.Map.member
to check if a key exists in the map.Map.fromFoldable
initializes a new map with given key-value pairs.Now that we have explored map functionalities, let’s dive deeper into other aspects of PureScript.