Created
May 5, 2019 20:09
-
-
Save jship/942af4e6867c4c74b66c9bab0869918f to your computer and use it in GitHub Desktop.
This file contains 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
-- 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