Skip to content

Instantly share code, notes, and snippets.

@xfire
Created February 5, 2012 20:31
Show Gist options
  • Save xfire/1747802 to your computer and use it in GitHub Desktop.
Save xfire/1747802 to your computer and use it in GitHub Desktop.
haskell lenses on recursive data structures
{-# 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 TD = TD { name_ :: String
, td_ :: TD
}
| TNil
deriving Show
-- template haskell magic to create accessor functions
$( deriveLenses ''TD )
testdata = TD "level 1" $ TD "level 2" $ TD "level 3" $ TNil
setNameOn3 :: TD -> String -> TD
setNameOn3 d = d `update` (td . td . name)
main :: IO ()
main = do
print $ setNameOn3 testdata "blub"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment