diff --git a/src/Data/Array.purs b/src/Data/Array.purs index deeb2a24..358ab570 100644 --- a/src/Data/Array.purs +++ b/src/Data/Array.purs @@ -79,8 +79,10 @@ module Data.Array , sortWith , slice , take + , takeEnd , takeWhile , drop + , dropEnd , dropWhile , span , group @@ -495,6 +497,11 @@ foreign import slice :: forall a. Int -> Int -> Array a -> Array a -- | array. foreign import take :: forall a. Int -> Array a -> Array a +-- | Keep only a number of elements from the end of an array, creating a new +-- | array. +takeEnd :: forall a. Int -> Array a -> Array a +takeEnd n xs = drop (length xs - n) xs + -- | Calculate the longest initial subarray for which all element satisfy the -- | specified predicate, creating a new array. takeWhile :: forall a. (a -> Boolean) -> Array a -> Array a @@ -503,6 +510,10 @@ takeWhile p xs = (span p xs).init -- | Drop a number of elements from the start of an array, creating a new array. foreign import drop :: forall a. Int -> Array a -> Array a +-- | Drop a number of elements from the start of an array, creating a new array. +dropEnd :: forall a. Int -> Array a -> Array a +dropEnd n xs = take (length xs - n) xs + -- | Remove the longest initial subarray for which all element satisfy the -- | specified predicate, creating a new array. dropWhile :: forall a. (a -> Boolean) -> Array a -> Array a diff --git a/test/Test/Data/Array.purs b/test/Test/Data/Array.purs index 2436afb1..f97314b8 100644 --- a/test/Test/Data/Array.purs +++ b/test/Test/Data/Array.purs @@ -251,6 +251,11 @@ testArray = do assert $ (A.takeWhile (_ /= 3) [1, 2, 3]) == [1, 2] assert $ (A.takeWhile (_ /= 1) nil) == nil + log "take should keep the specified number of items from the end of an array, discarding the rest" + assert $ (A.takeEnd 1 [1, 2, 3]) == [3] + assert $ (A.takeEnd 2 [1, 2, 3]) == [2, 3] + assert $ (A.takeEnd 1 nil) == nil + log "drop should remove the specified number of items from the front of an array" assert $ (A.drop 1 [1, 2, 3]) == [2, 3] assert $ (A.drop 2 [1, 2, 3]) == [3] @@ -261,6 +266,11 @@ testArray = do assert $ (A.dropWhile (_ /= 2) [1, 2, 3]) == [2, 3] assert $ (A.dropWhile (_ /= 1) nil) == nil + log "drop should remove the specified number of items from the end of an array" + assert $ (A.dropEnd 1 [1, 2, 3]) == [1, 2] + assert $ (A.dropEnd 2 [1, 2, 3]) == [1] + assert $ (A.dropEnd 1 nil) == nil + log "take and drop should treat negative arguments as zero" assert $ (A.take (-2) [1, 2, 3]) == nil assert $ (A.drop (-2) [1, 2, 3]) == [1, 2, 3]