Skip to content

Don't force more than necessary in Data.List.Lazy take #139

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 22, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/Data/List/Lazy.purs
Original file line number Diff line number Diff line change
Expand Up @@ -509,10 +509,11 @@ slice start end xs = take (end - start) (drop start xs)
-- |
-- | Running time: `O(n)` where `n` is the number of elements to take.
take :: forall a. Int -> List a -> List a
take n = List <<< map (go n) <<< unwrap
take n = if n <= 0
then const nil
else List <<< map (go n) <<< unwrap
where
go :: Int -> Step a -> Step a
go i _ | i <= 0 = Nil
go _ Nil = Nil
go n' (Cons x xs) = Cons x (take (n' - 1) xs)

Expand Down
6 changes: 6 additions & 0 deletions test/Test/Data/List/Lazy.purs
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,12 @@ testListLazy = do
assert $ (take 2 (l [1, 2, 3])) == l [1, 2]
assert $ (take 1 nil') == nil'

log "take should evaluate exactly n items which we needed"
assert let oops x = 0 : oops x
xs = 1 : defer oops
in take 1 xs == l [1]
-- If `take` evaluate more than once, it would crash with a stack overflow

log "takeWhile should keep all values that match a predicate from the front of an list"
assert $ (takeWhile (_ /= 2) (l [1, 2, 3])) == l [1]
assert $ (takeWhile (_ /= 3) (l [1, 2, 3])) == l [1, 2]
Expand Down