List rooted trees: Difference between revisions
Content added Content deleted
(→{{header|Haskell}}: minor tidying of test) |
|||
Line 387: | Line 387: | ||
A variant which uses Data.Tree |
A variant which uses Data.Tree |
||
<lang haskell>import Data. |
<lang haskell>import Data.List (nub, sortBy, foldl') --' strict variant of foldl |
||
import Data.List (nub, sortBy, foldl') --' strict variant of foldl |
|||
import Data.Ord (comparing) |
import Data.Ord (comparing) |
||
import Data.Tree |
|||
bagPatterns :: Int -> [String] |
bagPatterns :: Int -> [String] |
||
Line 399: | Line 399: | ||
parentIndexPermutations :: Int -> [[Int]] |
parentIndexPermutations :: Int -> [[Int]] |
||
parentIndexPermutations = |
parentIndexPermutations = |
||
sequenceA . (enumFromTo 0 |
sequenceA . fmap (enumFromTo 0) . enumFromTo 0 . subtract 2 |
||
treeFromParentIndices :: [Int] -> Tree Int |
treeFromParentIndices :: [Int] -> Tree Int |
||
treeFromParentIndices pxs = |
treeFromParentIndices pxs = |
||
foldl' --' strict variant of foldl |
foldl' --' strict variant of foldl |
||
go |
|||
go (Node 0 []) (zip [1 .. (length pxs)] pxs) |
|||
(Node 0 []) |
|||
(zip [1 .. (length pxs)] pxs) |
|||
⚫ | |||
let root = rootLabel tree |
|||
go tree tplIP = |
|||
let root = rootLabel tree |
|||
nest = subForest tree |
|||
in Node |
|||
⚫ | |||
root |
|||
(if root == snd tplIP |
|||
then nest ++ [Node (fst tplIP) []] |
|||
⚫ | |||
depthSortedTree |
depthSortedTree |
||
Line 420: | Line 422: | ||
depthSortedTree = go |
depthSortedTree = go |
||
where |
where |
||
go tree |
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) |
|||
commasFromTree :: Tree a -> String |
commasFromTree :: Tree a -> String |
||
commasFromTree = |
commasFromTree tree = "(" ++ concat (commasFromTree <$> subForest tree) ++ ")" |
||
⚫ | |||
go tree = "(" ++ concat (go <$> subForest tree) ++ ")" |
|||
main :: IO () |
main :: IO () |