Skip to content

Instantly share code, notes, and snippets.

@xfire
Created February 5, 2012 20:06
Show Gist options
  • Save xfire/1747728 to your computer and use it in GitHub Desktop.
Save xfire/1747728 to your computer and use it in GitHub Desktop.
play with haskell lenses
{-# LANGUAGE TemplateHaskell, FlexibleContexts #-}
import Data.Lenses
import Data.Lenses.Template
-- data structures to work on
-- for fields ending with an underscore, special lens accessor functions
-- can be created with "deriveLenses"
data Address = Address { street_ :: String
, houseNumber_ :: Int
, city_ :: String
, postcode_ :: String
} deriving Show
data Person = Person { name_ :: String
, age_ :: Int
, address_ :: Address
} deriving Show
-- template haskell magic to create accessor functions
$( deriveLenses ''Address )
$( deriveLenses ''Person )
-- test data
myhome = Address "Foostreet" 42 "Heerbrugg" "12345"
myself = Person "Rico" 32 myhome
-- first naive aproach
otherStreet = let a = myself `fetch` address
a' = a `update` street $ "blub"
in myself `update` address $ a'
-- better when combining lenses
otherStreet' = myself `update` (address . street) $ "blub"
main :: IO ()
main = do
print $ myself `fetch` (address . street)
print $ otherStreet' `fetch` (address . street)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment