My take on pretty printing a rose tree like the unix tree
command does. Inspired by
this
blog post of a version in OCaml.
It is pure and idiomatic without using any library functions. Thanks to laziness, it doesn't wait to return until the whole string is built. As such it will print a finite prefix of large or infinite trees (see example below).
I might make an actual command line tool out of this at some point.
-- | Rose tree of 'String', good for representing unix directory structure
data Tree = Node String [Tree]
-- | Show instance for rendering 'Tree' like the unix @tree@ command
instance Show Tree where
show (Node x subtree) = x ++ go subtree ""
where
go [] _ = ""
go [Node x ts] indent =
"\n" ++ indent ++ "└── " ++ x ++ go ts (indent ++ " ")
go (Node x ts : xs) indent =
"\n" ++ indent ++ "├── " ++ x ++ go ts (indent ++ "│ ") ++ go xs indent
-- | An example 'Tree'
test :: Tree
test = Node "." [ Node "a" [ Node "aa" []
, Node "ab" [ Node "aba" []]
]
, Node "b" [ Node "ba" []
, Node "bb" [ Node "bba" []
, Node "bbb" []
]
]
, Node "c" [ Node "ca" []
, Node "cb" [ Node "cba" [ Node "cbaa" []
, Node "cbab" []
]
]
, Node "cc" []
, Node "cd" (repeat (Node "cda" [])) -- repeat forever
]
]
Output:
ghci> print test
.
├── a
│ ├── aa
│ └── ab
│ └── aba
├── b
│ ├── ba
│ └── bb
│ ├── bba
│ └── bbb
└── c
├── ca
├── cb
│ └── cba
│ ├── cbaa
│ └── cbab
├── cc
└── cd
├── cda
├── cda
├── cda
^C ├── cda
├── cda
├── cda
Interrupted.
This is the OCaml version from the linked article: