Skip to content

Instantly share code, notes, and snippets.

@cdepillabout
Last active August 3, 2017 17:07
Show Gist options
  • Save cdepillabout/af414dcb9032a29e1ec4562edd7209d3 to your computer and use it in GitHub Desktop.
Save cdepillabout/af414dcb9032a29e1ec4562edd7209d3 to your computer and use it in GitHub Desktop.
small example of using lens
#!/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)
@cdepillabout
Copy link
Author

When run, this prints the following:

Bar 3 "hello"
Just 3
Bar 6 "hello"

@cdepillabout
Copy link
Author

This gist is for my blog post GHC Warnings You Should Use in Addition to -Wall.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment