List rooted trees: Difference between revisions

m
m (→‎{{header|Haskell}}: (used foldTree))
Line 385:
</pre>
 
A variant whichexpressed usesin terms of Data.Tree
 
<lang haskell>import Data.List (nub, sortBy, foldl') --' strict variant of foldl
import Data.Tree (Tree(..), foldTree)
import Data.Ord (comparing)
import Data.Tree
 
bagPatterns :: Int -> [String]
Line 396:
bracketsFromTree . depthSortedTree . treeFromParentIndices <$>
parentIndexPermutations n
 
---------------------------TEST----------------------------
main :: IO ()
main = putStrLn . unlines $ bagPatterns 5</lang>
 
------------------------DEFINITIONS------------------------
depthSortedTree
:: (Enum a, Num a, Ord a)
=> Tree a -> Tree a
depthSortedTree = gotree
| null (subForest tree) = Node 0 []
| otherwise =
let xs = godepthSortedTree <$> subForest tree
in Node
(1succ +$ foldr ((+) . rootLabel) 0 xs)
(sortBy (flip (comparing rootLabel)) xs)
 
bracketsFromTree :: Tree a -> String
bracketsFromTree = foldTree (\_ xs -> '(' : (concat xs ++ ")"))
 
parentIndexPermutations :: Int -> [[Int]]
Line 401 ⟶ 420:
 
treeFromParentIndices :: [Int] -> Tree Int
treeFromParentIndices pxsixs =
foldl' --' strict variant of foldl
go
(Node 0 [])
(zip [1 .. (length pxs)ixs] pxsixs)
where
go tree tplIP(i, x) = Node root forest
where
let root = rootLabel tree
nestroot = subForestrootLabel tree
nest = forestsubForest tree
in Node root forest
| root == snd tplIP = nest ++ [Node (fst tplIP) []]
| root |== otherwisex = (`go`nest tplIP)++ <$>[Node nesti []]
| otherwise = (`go` (i, x)) <$> nest</lang>
in Node root forest
 
depthSortedTree
:: (Num a, Ord a)
=> Tree a -> Tree a
depthSortedTree = go
where
go tree
| null (subForest tree) = Node 0 []
| otherwise =
let xs = go <$> subForest tree
in Node
(1 + foldr ((+) . rootLabel) 0 xs)
(sortBy (flip (comparing rootLabel)) xs)
 
bracketsFromTree :: Tree a -> String
bracketsFromTree = foldTree (\_ xs -> '(' : (concat xs ++ ")"))
 
main :: IO ()
main = putStrLn . unlines $ bagPatterns 5</lang>
{{Out}}
<pre>(()()()())
9,655

edits