Last active
August 3, 2017 17:07
-
-
Save cdepillabout/af414dcb9032a29e1ec4562edd7209d3 to your computer and use it in GitHub Desktop.
small example of using lens
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 --resolver lts-9.0 script --package transformers --package lens -- -Wall | |
-- If you have stack installed, all you need to do is make this file executable | |
-- and you can run it from the command line. | |
module Main where | |
import Control.Lens (Prism', Traversal', _1, _2, preview, prism', set) | |
data Foo | |
= Bar Int String | |
| Baz | |
deriving Show | |
_Bar :: Prism' Foo (Int, String) | |
_Bar = | |
prism' | |
(\(int, string) -> Bar int string) | |
(\foo -> | |
case foo of | |
Baz -> Nothing | |
Bar int string -> Just (int, string) | |
) | |
_Baz :: Prism' Foo () | |
_Baz = | |
prism' | |
(\() -> Baz) | |
(\foo -> | |
case foo of | |
Baz -> Just () | |
Bar _ _ -> Nothing | |
) | |
barIntTraversal :: Traversal' Foo Int | |
barIntTraversal = _Bar . _1 | |
barStringTraversal :: Traversal' Foo String | |
barStringTraversal = _Bar . _2 | |
main :: IO () | |
main = do | |
let bar = Bar 3 "hello" | |
print bar | |
print (preview barIntTraversal bar) | |
print (set barIntTraversal 6 bar) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When run, this prints the following: