Last active
December 31, 2024 00:11
-
-
Save rybla/953cdd7b8a54ae7f1fcfea11d5fef38b to your computer and use it in GitHub Desktop.
printing levels of a tree on separate lines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Solution 2: using breadth-first search | |
module Main where | |
import Prelude | |
import Data.Array as Array | |
import Data.Foldable (foldM, traverse_) | |
import Data.Traversable (traverse) | |
import Data.Tuple.Nested ((/\)) | |
import Effect (Effect) | |
import Effect.Class.Console as Console | |
data Tree a = B a (Array (Tree a)) | |
printLevels :: forall a. Show a => Tree a -> Effect Unit | |
printLevels t = go [ t ] | |
where | |
go ts | Array.null ts = pure unit | |
go ts = do | |
as /\ ts' <- ts | |
# foldM | |
( \(as /\ ts') (B a ts'') -> do | |
pure $ (as <> [ a ]) /\ (ts' <> ts'') | |
) | |
([] /\ []) | |
Console.logShow as | |
go ts' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Solution 1: using mergeLevels | |
module MergeLevels where | |
import Prelude | |
import Data.Array as Array | |
import Data.Foldable (traverse_) | |
import Effect (Effect) | |
import Effect.Class.Console as Console | |
data Tree a = B a (Array (Tree a)) | |
printLevels :: forall a. Show a => Tree a -> Effect Unit | |
printLevels t = printLevels' t # traverse_ Console.logShow | |
printLevels' :: forall a. Show a => Tree a -> Array (Array String) | |
printLevels' (B a ts) = [ show a ] Array.: (ts # map printLevels' # mergeLevels) | |
mergeLevels :: Array (Array (Array String)) -> Array (Array String) | |
mergeLevels = Array.foldl f [] | |
where | |
f ls1 ls2 = Array.zipWith append ls1 ls2 <> | |
( if Array.length ls1 < Array.length ls2 then | |
Array.drop (Array.length ls1) ls2 | |
else | |
Array.drop (Array.length ls2) ls1 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment