Skip to content

Instantly share code, notes, and snippets.

Last active August 3, 2017 17:07
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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 =
(\(int, string) -> Bar int string)
(\foo ->
case foo of
Baz -> Nothing
Bar int string -> Just (int, string)
_Baz :: Prism' Foo ()
_Baz =
(\() -> 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)
Copy link

When run, this prints the following:

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

Copy link

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