Skip to content

Instantly share code, notes, and snippets.

@kana-sama
Created December 15, 2020 23:36
Show Gist options
  • Save kana-sama/b934a822986265486666d0c1a9e59cbf to your computer and use it in GitHub Desktop.
Save kana-sama/b934a822986265486666d0c1a9e59cbf to your computer and use it in GitHub Desktop.
import Control.Concurrent.Async (mapConcurrently_)
import Control.Monad (unless)
import Data.IORef (atomicModifyIORef, newIORef)
import qualified Data.Set as Set
data Tree a
= Leaf a
| Node (Tree a) (Tree a)
deriving (Eq, Ord)
printLeaves :: (Ord a, Show a) => Tree a -> IO ()
printLeaves tree = do
visited <- newIORef Set.empty
go visited tree
where
go visited element = do
isVisitedBefore <- atomicModifyIORef visited \visited ->
(Set.insert element visited, Set.member element visited)
unless isVisitedBefore do
case element of
Leaf x -> print x
Node l r -> mapConcurrently_ (go visited) [l, r]
main :: IO ()
main =
printLeaves $
let x = Node (Leaf 1) (Leaf 2)
in Node (Node x (Leaf 3)) x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment