Skip to content

Instantly share code, notes, and snippets.

@nattybear
Last active July 27, 2022 15:51
Show Gist options
  • Save nattybear/ed395f1a35ef18badda4f7a0137a3254 to your computer and use it in GitHub Desktop.
Save nattybear/ed395f1a35ef18badda4f7a0137a3254 to your computer and use it in GitHub Desktop.
module Tree where
data Tree a = Leaf a
| Node (Tree a) (Tree a)
deriving Show
type WithCounter a = Int -> (a, Int)
numberOfLeaves :: Tree a -> Integer
numberOfLeaves (Leaf _) = 1
numberOfLeaves (Node l r) = numberOfLeaves l + numberOfLeaves r
relabel :: Tree a -> WithCounter (Tree a)
relabel (Leaf x) = \i -> (Leaf x, i+1)
relabel (Node l r) = relabel l `next` \l' ->
relabel r `next` \r' ->
pure' (Node l' r')
next :: WithCounter a -> (a -> WithCounter b) -> WithCounter b
f `next` g = \i -> let (r, i') = f i
in g r i'
pure' :: a -> WithCounter a
pure' x = \i -> (x, i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment