Skip to content

Instantly share code, notes, and snippets.

@bruno-cadorette
Created November 9, 2015 05:38
Show Gist options
  • Select an option

  • Save bruno-cadorette/8bc19dd53b26ae993481 to your computer and use it in GitHub Desktop.

Select an option

Save bruno-cadorette/8bc19dd53b26ae993481 to your computer and use it in GitHub Desktop.
Read a rose tree separated by new lines and tabs and transform it to a Data.Tree
import Data.List
import Data.Tree
import Control.Arrow (first)
import Data.Function (on)
toHierarchical :: String -> [(Int, [String])]
toHierarchical = map simplify . groupBy ((==) `on` fst) . map (first length . span (== '\t')) . lines
where
simplify = first head . unzip
toTree :: Ord t => [(t, [a])] -> [Tree a]
toTree [] = []
toTree ((pos, nodes):xs) = mapOnlyLast nodes ++ toTree xs'
where
mapOnlyLast [] = []
mapOnlyLast [x] = [Node x (toTree childs)]
mapOnlyLast (x:xs) = Node x [] : mapOnlyLast xs
(childs, xs') = span (\(i,_)-> i > pos) xs
main = (drawForest . toTree . toHierarchical) <$> readFile "testTab.txt" >>= putStrLn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment