Skip to content

Instantly share code, notes, and snippets.

@ulidtko
Created April 26, 2016 12:24
Show Gist options
  • Save ulidtko/af2947ada9699fdf56788e0feaad89bf to your computer and use it in GitHub Desktop.
Save ulidtko/af2947ada9699fdf56788e0feaad89bf to your computer and use it in GitHub Desktop.
Imperative tree traversal sample
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Control.Applicative
import Data.Foldable
import Data.Traversable
import Data.IORef
data BinTree a = Leaf a | Node (BinTree a) (BinTree a)
deriving (Functor, Foldable, Traversable, Show)
exTree :: BinTree Int
exTree = (Leaf 1 `Node` (Leaf 50 `Node` Leaf 20)) `Node` (Leaf 100)
main :: IO ()
main = do
sum :: IORef Int <- newIORef 0
flip traverse exTree $ \x -> do
modifyIORef sum (+x)
print x
putStr "Total: "
print =<< readIORef sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment