Skip to content

Instantly share code, notes, and snippets.

@AndrasKovacs
Created April 1, 2013 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrasKovacs/5285582 to your computer and use it in GitHub Desktop.
Save AndrasKovacs/5285582 to your computer and use it in GitHub Desktop.
{-# LANGUAGE TupleSections, DeriveTraversable, DeriveFoldable, DeriveFunctor #-}
import Control.Monad.State
import Data.Traversable
import Data.Foldable
import qualified Data.Map as M
data Tree a = Empty | Tree a (Tree a) (Tree a)
deriving (Show, Functor, Foldable, Traversable)
numTree :: Ord a => Tree a -> Tree Int
numTree = (`evalState` (0, M.empty)) . traverse go where
go a = state $ \s@(n, m) ->
maybe (n, (n + 1, M.insert a n m)) (,s) (M.lookup a m)
tree = Tree 0 (Tree 3 (Tree 0 Empty Empty) (Tree 2 Empty Empty)) (Tree 4 Empty Empty)
main = print $ numTree tree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment