on master help sign in
Add a filter function

Bring Array library more in line with Dict and Set which now have this function as well.

commit663f5652c6793b1824d5977e16d8ba5ff51099c3 authorEvan Czaplicki <info@elm-lang.org> dateWed 16 Apr 2014, 16:29 (13 years ago) parent3fb4ea1
2 files changed+11
libraries/Array.elm+10 tests/elm/Test/Array.elm+1
libraries/Array.elm+10
@@ -96,6 +96,16 @@ foldl = Native.Array.foldl
9696foldr : (a -> b -> b) -> b -> Array a -> b
9797foldr = Native.Array.foldr
9898
99+{-| Keep only elements that satisfy the predicate:
100+
101+ filter isEven (fromList [1..6]) == (fromList [2,4,6])
102+-}
103+filter : (a -> Bool) -> Array a -> Array a
104+filter isOkay arr =
105+ let update x xs = if isOkay x then Native.Array.push x xs else xs
106+ in
107+ Native.Array.foldl update Native.Array.empty arr
108+
99109{-| Return an empty array.
100110
101111 length empty == 0
tests/elm/Test/Array.elm+1
@@ -43,5 +43,6 @@ tests =
4343 , test "foldl" <| assertEqual (Array.foldl (::) [] (Array.fromList [1,2,3])) [3,2,1]
4444 , test "foldr" <| assertEqual (Array.foldr (+) 0 (Array.repeat 3 5)) 15
4545 , test "foldr 2" <| assertEqual (Array.foldr (::) [] (Array.fromList [1,2,3])) [1,2,3]
46+ , test "filter" <| assertEqual (Array.filter (\x -> x `mod` 2 == 0) (Array.fromList [1..6])) (Array.fromList [2,4,6])
4647 ]
4748 in List.concat [creationTests, basicsTests, getAndSetTests, takingArraysApartTests, mappingAndFoldingTests]