Skip to content

Instantly share code, notes, and snippets.

@xfire
Created July 6, 2011 19:22
Show Gist options
  • Save xfire/1068102 to your computer and use it in GitHub Desktop.
Save xfire/1068102 to your computer and use it in GitHub Desktop.
list zipper
-- little helper function
-- f3 (f2 (f1 x)) == x -: f1 -: f2 -: f3
(-:) x f = f x
-- the list zipper simply split the list in two parts.
type ListZipper a = ([a], [a])
makeListZipper :: [a] -> ListZipper a
makeListZipper l = (l, [])
forward :: ListZipper a -> ListZipper a
forward (x:xs, zs) = (xs, x:zs)
back :: ListZipper a -> ListZipper a
back (xs, z:zs) = (z:xs, zs)
toHead :: ListZipper a -> ListZipper a
toHead (xs, []) = (xs, [])
toHead z = toHead (back z)
toEnd :: ListZipper a -> ListZipper a
toEnd ([], zs) = ([], zs)
toEnd z = toEnd (forward z)
modify :: (a -> a) -> ListZipper a -> ListZipper a
modify f (x:xs, zs) = (f x : xs, zs)
attach :: [a] -> ListZipper a -> ListZipper a
attach l (_, zs) = (l, zs)
main = do
let sample = [1..8]
let l = makeListZipper sample -: forward -: forward -: (modify $ const 42) -: forward -: forward -: (attach [99, 88]) -: toHead
mapM_ putStrLn [ show sample
, "------------------------------------------------------"
, "change 3 to 42 and replace [5,6,7,8] with [99, 88]"
, "------------------------------------------------------"
, show $ fst l
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment