Skip to content

Commit 6c8aaad

Browse files
mlms13paf31
authored andcommitted
Avoid infinite loop possibility with takeEnd (#133)
* Avoid infinite loop possibility with takeEnd * Protect `take` against infinite recursion
1 parent 55b1848 commit 6c8aaad

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

src/Data/List.purs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -517,7 +517,7 @@ slice start end xs = take (end - start) (drop start xs)
517517
take :: forall a. Int -> List a -> List a
518518
take = go Nil
519519
where
520-
go acc 0 _ = reverse acc
520+
go acc n _ | n < 1 = reverse acc
521521
go acc _ Nil = reverse acc
522522
go acc n (x : xs) = go (x : acc) (n - 1) xs
523523

@@ -541,7 +541,7 @@ takeWhile p = go Nil
541541
-- |
542542
-- | Running time: `O(n)` where `n` is the number of elements to drop.
543543
drop :: forall a. Int -> List a -> List a
544-
drop 0 xs = xs
544+
drop n xs | n < 1 = xs
545545
drop _ Nil = Nil
546546
drop n (x : xs) = drop (n - 1) xs
547547

test/Test/Data/List.purs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,21 +225,25 @@ testList = do
225225
assert $ (take 1 (l [1, 2, 3])) == l [1]
226226
assert $ (take 2 (l [1, 2, 3])) == l [1, 2]
227227
assert $ (take 1 nil) == nil
228+
assert $ (take 0 (l [1, 2])) == l []
229+
assert $ (take (-1) (l [1, 2])) == l []
228230

229231
log "takeEnd should keep the specified number of items from the end of an list, discarding the rest"
230232
assert $ (takeEnd 1 (l [1, 2, 3])) == l [3]
231233
assert $ (takeEnd 2 (l [1, 2, 3])) == l [2, 3]
232234
assert $ (takeEnd 1 nil) == nil
235+
assert $ (takeEnd 2 (l [1])) == l [1]
233236

234237
log "takeWhile should keep all values that match a predicate from the front of an list"
235238
assert $ (takeWhile (_ /= 2) (l [1, 2, 3])) == l [1]
236239
assert $ (takeWhile (_ /= 3) (l [1, 2, 3])) == l [1, 2]
237240
assert $ (takeWhile (_ /= 1) nil) == nil
238241

239-
log "dropE should remove the specified number of items from the front of an list"
242+
log "drop should remove the specified number of items from the front of an list"
240243
assert $ (drop 1 (l [1, 2, 3])) == l [2, 3]
241244
assert $ (drop 2 (l [1, 2, 3])) == l [3]
242245
assert $ (drop 1 nil) == nil
246+
assert $ (drop (-1) (l [1, 2, 3])) == l [1, 2, 3]
243247

244248
log "dropEnd should remove the specified number of items from the end of an list"
245249
assert $ (dropEnd 1 (l [1, 2, 3])) == l [1, 2]

0 commit comments

Comments
 (0)