Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions containers/src/Data/Tree.hs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ module Data.Tree(
-- * Elimination
, foldTree
, flatten
, filterTree
, levels
, leaves
, edges
Expand All @@ -61,6 +62,7 @@ import Data.Bits ((.&.))
import Data.Foldable (toList)
import qualified Data.Foldable as Foldable
import Data.List.NonEmpty (NonEmpty(..))
import Data.Maybe (mapMaybe)
import Data.Traversable (foldMapDefault)
import Control.Monad (liftM)
import Control.Monad.Fix (MonadFix (..), fix)
Expand Down Expand Up @@ -390,6 +392,41 @@ draw (Node x ts0) = lines x ++ drawSubTrees ts0
flatten :: Tree a -> [a]
flatten = toList

-- | Apply a predicate on a tree and prune off branches
-- when a node does not satisfy the predicate.
--
-- ==== __Examples__
--
-- >>> filterTree (< 3) (Node 1 [Node 2 [], Node 3 [Node 4 [], Node 1 [Node 2 []]]])
-- Just (Node 1 [Node 2 []])
--
-- @
-- 1 1
-- | |
-- +- 2 `- 2
-- |
-- `- 3 =>
-- |
-- +- 4
-- |
-- `- 1
-- |
-- `- 2
-- @
--
-- @since FIXME

filterTree
:: (a -> Bool)
-- ^ Predicate
-> Tree a
-> Maybe (Tree a)
filterTree predicate (Node root forest)
| predicate root = Just (Node root (pruneForest forest))
| otherwise = Nothing
where
pruneForest = mapMaybe (filterTree predicate)

-- | Returns the list of nodes at each level of the tree.
--
-- @
Expand Down