Skip to content

Instantly share code, notes, and snippets.

@russmatney
Created May 12, 2018 03:37
Show Gist options
  • Save russmatney/4d8932efaa25d2a68cb0a54eff13e7b4 to your computer and use it in GitHub Desktop.
Save russmatney/4d8932efaa25d2a68cb0a54eff13e7b4 to your computer and use it in GitHub Desktop.
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
-- Just 99
print $ bob ^? inventory . ix "gold" . value
-- Just 99
print $ bob ^? inventory . at "doesnotexist" . _Just . value
-- Nothing
print $ bob ^? inventory . ix "doesnotexist" . value
-- Nothing
print "Bob finds a diamond"
let bobFindsDiamond = bob & inventory . at "diamond" ?~ (Item 1000 1)
bobFindsDiamond' = bob & inventory . at "diamond" .~ Just (Item 1000 1)
print $ bobFindsDiamond ^? inventory . ix "diamond"
-- Just (Item 1000 1)
print $ bobFindsDiamond' ^? inventory . ix "diamond"
-- Just (Item 1000 1)
print "Bob loses his gold, some points, and is sad"
let bobLosesGold = bob
& inventory . at "gold" .~ Nothing
& score %~ (\sc -> sc - 41)
& userName .~ UserName "Sad Bob"
-- Note the differences in `^./^?/at/ix` usage
print $ bobLosesGold ^? inventory . at "gold"
-- Just Nothing
print $ bobLosesGold ^. inventory . at "gold"
-- Nothing
print $ bobLosesGold ^? inventory . ix "gold"
-- Nothing
-- This won't compile without an instance of Monoid for "Item".
-- If you implement that instance, and run this, it will assume you
-- wanted to use that Monoid instance, and return it's mempty for you.
-- print $ bobLosesGold ^. inventory . ix "gold"
print $ bobLosesGold ^. score
-- 1
print $ bobLosesGold ^. userName
-- UserName "Sad Bob"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment