Created
December 15, 2020 23:36
-
-
Save kana-sama/b934a822986265486666d0c1a9e59cbf to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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