Create a gist now

Instantly share code, notes, and snippets.

@tfausak /Main1.fr
Last active Oct 14, 2015

module Main1 where
data HashSet a = native java.util.HashSet where
native new :: () -> STMutable s (HashSet a)
native size :: Mutable s (HashSet a) -> ST s Int
native add :: Mutable s (HashSet a) -> a -> ST s Bool
native remove :: Mutable s (HashSet a) -> a -> ST s Bool
main :: IO ()
main = do
set <- HashSet.new ()
println =<< set.size -- 0
added <- set.add "hello"
println added -- true
println =<< set.size -- 1
added <- set.add "hello"
println added -- false
println =<< set.size -- 1
removed <- set.remove "hello"
println removed -- true
println =<< set.size -- 0
removed <- set.remove "hello"
println removed -- false
println =<< set.size -- 0
module Main2 where
data HashSet a = native java.util.HashSet where
native new :: () -> STMutable s (HashSet a)
native size :: Mutable s (HashSet a) -> ST s Int
native add :: Mutable s (HashSet a) -> a -> ST s Bool
fromList :: [a] -> STMutable s (HashSet a)
fromList list = do
set <- HashSet.new ()
let addAll :: [a] -> Mutable s (HashSet a) -> STMutable s (HashSet a)
addAll [] s = pure s
addAll (x : xs) s = do
s.add x
addAll xs s
addAll list set
toList :: Mutable s (HashSet a) -> ST s [a]
toList set = do
iterator <- set.iterator
let loop xs i = do
p <- i.hasNext
if p
then do
x <- i.next
loop (x : xs) i
else pure xs
loop [] iterator
main :: IO ()
main = do
set <- HashSet.fromList [1, 2, 3]
println =<< set.size -- 3
println =<< set.toList -- [3, 2, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment