Skip to content

Instantly share code, notes, and snippets.

@jship
Created May 5, 2019 20:09
Show Gist options
  • Save jship/942af4e6867c4c74b66c9bab0869918f to your computer and use it in GitHub Desktop.
Save jship/942af4e6867c4c74b66c9bab0869918f to your computer and use it in GitHub Desktop.
-- subForestWithParent returns the subforest of the input 'Tree', where each
-- node value in each 'Tree' of the subforest is paired with the value of its
-- parent node.
--
-- ghci> let tree = Node 1 [Node 2 [Node 4 []], Node 3 [Node 5 [Node 7 []], Node 6 []]]
-- ghci> putStrLn . drawTree . fmap show $ tree
-- 1
-- |
-- +- 2
-- | |
-- | `- 4
-- |
-- `- 3
-- |
-- +- 5
-- | |
-- | `- 7
-- |
-- `- 6
--
-- ghci> putStrLn . drawForest . fmap (fmap show) . subForestWithParent $ tree
-- (1,2)
-- |
-- `- (2,4)
--
-- (1,3)
-- |
-- +- (3,5)
-- | |
-- | `- (5,7)
-- |
-- `- (3,6)
subForestWithParent :: Tree a -> Forest (a, a)
subForestWithParent (Node n ts) = fmap (go n) ts where
go :: a -> Tree a -> Tree (a, a)
go parentLabel Node {rootLabel, subForest} = Node
{ rootLabel = (parentLabel, rootLabel)
, subForest = fmap (go rootLabel) subForest
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment