Created
April 26, 2016 12:24
-
-
Save ulidtko/af2947ada9699fdf56788e0feaad89bf to your computer and use it in GitHub Desktop.
Imperative tree traversal sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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