Skip to content

Instantly share code, notes, and snippets.

View russmatney's full-sized avatar

Russell Matney russmatney

View GitHub Profile
fancySetExamples :: IO ()
fancySetExamples = do
let bob = User (UserName "bob") 0 Nothing HM.empty
-- check out this multi-line string, why don't ya?
print "Bob changes his name to 'Bill'\
\, updates his score, and now owns Jeff's pet fish,\
\who is named Fitzgerald."
print $
bob
overExamples :: IO ()
overExamples = do
let fitz = Pet (PetName "Fitz")
let bob = User (UserName "bob") 0 (Just fitz) HM.empty
print "Bob scores a point. Way to go, Bob."
-- These all print bob with a score incremented by 1.
print $ bob & score %~ (\sc -> sc + 1)
print $ bob & score %~ (+1)
print $ over score (+1) bob
-- StorageError in a module somewhere
newtype StorageError = StorageError Text deriving (Eq, Show)
-- WebError wraps storage Error
data WebError
= WebTextError Text
| WebStorageError StorageError
deriving (Eq, Show)
-- Let's convert an 'Either StorageError a' to an 'Either WebError a'
atIxExamples :: IO ()
atIxExamples = do
-- Yep, you can use apostrophes in var names. Not that you should...
let bob'sInventory = HM.fromList [ ("gold", Item 99 10)
, ("silver", Item 10 9)
]
bob = User (UserName "bob") 42 Nothing bob'sInventory
print "Printing Bob's gold value"
print $ bob ^? inventory . at "gold" . _Just . value
atIxNonExamples :: IO ()
atIxNonExamples = do
let bob = User (UserName "bob") 42 Nothing HM.empty
-- if you were doing this for-real, you would impl and use Data.Default
defaultGoldItem = Item 0 0
print "Return the value of Bob's gold, whether he has it or not."
print $ bob ^. inventory . at "gold" . non defaultGoldItem . value
-- 0
print $ bob ^? inventory . at "gold" . _Just . value
toListOfExamples :: IO ()
toListOfExamples = do
let tory = HM.fromList [ ("gold", Item 99 10)
, ("silver", Item 10 9)
]
bob = User (UserName "bob") 42 Nothing tory
print "A list of Bob's items"
print $ bob ^.. inventory . folded
-- [Item {_itemValue = 10, _itemWeight = 9},Item {_itemValue = 99, _itemWeight = 10}]
hasGotcha :: IO ()
hasGotcha = do
let bob = User (UserName "bob") 42 Nothing HM.empty
print "Has bob gold in his inventory?"
print $ has (inventory . at "gold") bob
-- True
hasGotchaIx :: IO ()
hasGotchaIx = do
let bob = User (UserName "bob") 42 Nothing HM.empty
print "Has bob gold in his inventory?"
print $ has (inventory . ix "gold") bob
-- False
let richBob = User (UserName "bob") 42 Nothing
$ HM.fromList [("gold", Item 10 10)]
print "Has bob gold in his inventory?"
hasn'tExample :: IO ()
hasn'tExample = do
let bob = User (UserName "bob") 42 Nothing HM.empty
print "Hasn't bob gold in his inventory?"
print $ hasn't (inventory . ix "gold") bob
-- True
-- As in, "Yes, he doesn't."
main :: IO ()
main = do
print "Running 'viewExamples'"
viewExamples
print "Running 'composedViewExamples'"
composedViewExamples
print "Running 'previewExamples'"
previewExamples