Skip to content

Instantly share code, notes, and snippets.

@DonaldKellett
Created December 31, 2018 14:53
Show Gist options
  • Save DonaldKellett/c406f2b6533f77352608c70f5208be01 to your computer and use it in GitHub Desktop.
Save DonaldKellett/c406f2b6533f77352608c70f5208be01 to your computer and use it in GitHub Desktop.
PureScript By Example - 3. Functions and Records - 3.15 Tests, Tests, Tests ... - Solutions to Exercises 2-4
module AddressBook where
-- Boilerplate code given in "3. Functions and Records" of "PureScript by Example"
import Prelude
import Control.Plus (empty)
import Data.List (List(..), filter, head, nubBy)
import Data.Maybe (Maybe, isJust)
type Entry = { firstName :: String, lastName :: String, address :: Address }
type Address = { street :: String, city :: String, state :: String }
type AddressBook = List Entry
showEntry :: Entry -> String
showEntry entry = entry.lastName <> ", " <> entry.firstName <> ": " <> showAddress entry.address
showAddress :: Address -> String
showAddress addr = addr.street <> ", " <> addr.city <> ", " <> addr.state
emptyBook :: AddressBook
emptyBook = empty
insertEntry :: Entry -> AddressBook -> AddressBook
insertEntry = Cons
findEntry :: String -> String -> AddressBook -> Maybe Entry
findEntry firstName lastName = head <<< filter (\entry -> entry.firstName == firstName && entry.lastName == lastName)
printEntry :: String -> String -> AddressBook -> Maybe String
printEntry firstName lastName = (map showEntry) <<< (findEntry firstName lastName)
-- 3.15 Exercises
-- Exercise 2
findEntryByStreetAddress :: String -> AddressBook -> Maybe Entry
findEntryByStreetAddress street = head <<< filter (\entry -> entry.address.street == street)
-- Exercise 3
addressBookHasName :: String -> String -> AddressBook -> Boolean
addressBookHasName firstName lastName = isJust <<< (findEntry firstName lastName)
-- Exercise 4
removeDuplicates :: AddressBook -> AddressBook
removeDuplicates = nubBy (\entry entry' -> entry.firstName == entry'.firstName && entry.lastName == entry'.lastName)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment