import "Prelude" hiding (length, contains, iter, for) import "Prelude" as Prelude import "JavaBuiltin" as Java importJava "java.util.ArrayList" where "Type of lists." data T a "Constructs a new list." @JavaName "" new :: () -> (T a) "Constructs a new list with initial capacity." @JavaName "" newC :: Integer -> (T a) "Adds an element to the list." add :: T a -> a -> () addAll :: T a -> [a] -> () "Gets the i:th element of the list." get :: T a -> Integer -> a "Sets the i:th element of the list." set :: T a -> Integer -> a -> a "Removes the i:th element of the list" remove :: T a -> Integer -> a "The current length of the list." @JavaName size length :: T a -> Integer contains :: T a -> a -> Boolean contains l a = loop 0 where len = length l loop i = if i >= len then False else if get l i == a then True else loop (i+1) "Converts the mutable list into immutable list. The original list must not be modified anymore." freeze :: T a -> [a] freeze = Java.unsafeCoerce "Iterates thru the list. The elements added during the iteration are also iterated." iter :: (a -> ()) -> T a -> () iter f l = loop 0 where loop i = if i >= length l then () else do f (get l i) ; loop (i+1) "'iter' with swapped parameter." for :: T a -> (a -> ()) -> () for l f = iter f l "Replaces every element of the list by the result of applying the element to the given function." mapInPlace :: (a -> a) -> T a -> T a mapInPlace f l = loop 0 where len = length l loop i = if i >= len then l else do set l i (f (get l i)) loop (i+1) "Pops the last element of the list until list becomes empty." popUntilEmpty :: T a -> (a -> ()) -> () popUntilEmpty l f = do len = length l if len == 0 then () else do f (remove l (len-1)) popUntilEmpty l f fromList :: [a] -> T a fromList l = do result = newC (Prelude.length l) addAll result l result