Last active
March 15, 2018 00:58
-
-
Save danclien/f0b08eb79783e268c57daf0e537b491b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env stack | |
{- | |
stack | |
script | |
--resolver lts-11.0 | |
--ghc-options -Wall | |
-} | |
{-# LANGUAGE RankNTypes #-} | |
import Control.Lens | |
import Data.Map | |
data Animal = | |
Animal | |
{ tags :: Int | |
} deriving (Show) | |
data Model = | |
Model | |
{ animals :: Map String Animal | |
} deriving (Show) | |
model :: Model | |
model = | |
Model | |
{ animals = fromList | |
[ ("jake", Animal { tags = 4 }) | |
, ("skitter", Animal { tags = 6 }) | |
] | |
} | |
modelToAnimals :: Lens' Model (Map String Animal) | |
modelToAnimals = lens animals (\oldModel newAnimals -> oldModel { animals = newAnimals }) | |
animalToTags :: Lens' Animal Int | |
animalToTags = lens tags (\oldAnimal newTags -> oldAnimal { tags = newTags }) | |
modelToTags :: String -> Traversal' Model Int | |
modelToTags name = modelToAnimals . ix name . animalToTags | |
jake :: Maybe Int | |
jake = preview (modelToTags "jake") model | |
main :: IO () | |
main = print jake -- Just 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment