Last active
August 29, 2015 14:02
-
-
Save beoliver/d533714a8e79eb18fb46 to your computer and use it in GitHub Desktop.
rose tree paths
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
import Data.Maybe | |
data Tree a = Node a [Tree a] deriving (Show) | |
t = Node 1 [ Node 2 [ Node 3 [] ], Node 4 [], Node 5 [ Node 6 [] ] ] | |
paths :: Tree a -> [[a]] | |
paths (Node n []) = [[n]] | |
paths (Node n xs) = map ((:) n . concat . paths) xs | |
-- paths t | |
-- [[1,2,3], [1,4], [1,5,6]] | |
filterPaths :: (a -> Bool) -> Tree a -> [[a]] | |
filterPaths f tree = catMaybes . map sequence $ g f tree | |
where g f (Node n []) = case (f n) of | |
True -> [[Just n]] | |
_ -> [[Nothing]] | |
g f (Node n ns) = case (f n) of | |
True -> map ((:) (Just n) . concat . (g f)) ns | |
_ -> [[Nothing]] | |
-- filterPaths (/= 2) t | |
-- [[1,4],[1,5,6]] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment