File tree Expand file tree Collapse file tree 2 files changed +9
-2
lines changed Expand file tree Collapse file tree 2 files changed +9
-2
lines changed Original file line number Diff line number Diff line change @@ -509,10 +509,11 @@ slice start end xs = take (end - start) (drop start xs)
509
509
-- |
510
510
-- | Running time: `O(n)` where `n` is the number of elements to take.
511
511
take :: forall a . Int -> List a -> List a
512
- take n = List <<< map (go n) <<< unwrap
512
+ take n = if n <= 0
513
+ then const nil
514
+ else List <<< map (go n) <<< unwrap
513
515
where
514
516
go :: Int -> Step a -> Step a
515
- go i _ | i <= 0 = Nil
516
517
go _ Nil = Nil
517
518
go n' (Cons x xs) = Cons x (take (n' - 1 ) xs)
518
519
Original file line number Diff line number Diff line change @@ -272,6 +272,12 @@ testListLazy = do
272
272
assert $ (take 2 (l [1 , 2 , 3 ])) == l [1 , 2 ]
273
273
assert $ (take 1 nil') == nil'
274
274
275
+ log " take should evaluate exactly n items which we needed"
276
+ assert let oops x = 0 : oops x
277
+ xs = 1 : defer oops
278
+ in take 1 xs == l [1 ]
279
+ -- If `take` evaluate more than once, it would crash with a stack overflow
280
+
275
281
log " takeWhile should keep all values that match a predicate from the front of an list"
276
282
assert $ (takeWhile (_ /= 2 ) (l [1 , 2 , 3 ])) == l [1 ]
277
283
assert $ (takeWhile (_ /= 3 ) (l [1 , 2 , 3 ])) == l [1 , 2 ]
You can’t perform that action at this time.
0 commit comments