Skip to content

Instantly share code, notes, and snippets.

@remorses
Created May 28, 2019 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remorses/74bfcd9419b951dcf5260c0a29c881de to your computer and use it in GitHub Desktop.
Save remorses/74bfcd9419b951dcf5260c0a29c881de to your computer and use it in GitHub Desktop.
breadth first search (bfs) for multiway trees implemented in haskell
data Tree a = Node a [Tree a]
traverseBF :: Tree a -> Tree a
traverseBF tree = tbf tree
where
tbf (Node x []) = Node x []
tbf (Node x xs) = Node x (map tbf $ xs)
nodeValue (Node a _) = a
nodes (Node _ []) = []
nodes (Node _ xs) = xs
instance (Show a) => Show (Tree a) where
show tree = show' 0 tree
where show' n t =
let
tabs = (replicate n '\t')
showNext x = '\n' : show' (n+1) x
in
case t of
(Node x []) -> tabs ++ show x
(Node x xs) -> tabs ++ show x ++ concatMap showNext xs
createTree =
Node 'A'[
Node 'B'[
Node 'C' [],
Node 'D' []
],
Node 'E' [
Node 'F' [],
Node 'G' [
Node 'H' [
Node 'I' []
]
]
]
]
main = do
let
t = createTree
print (traverseBF t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment