Commit b7139869 authored by David Feuer's avatar David Feuer Committed by Ben Gamari
Browse files

Improve some Foldable methods for NonEmpty

* `length` is improved by using the default definition,
  while `foldr1` is improved by using a custom one.

* Several methods had useless lazy pattern matches
  (i.e., the functions were actually strict in those arguments).
  Remove `~`s to clarify.

Reviewers: hvr, bgamari, mpickering, nomeata

Reviewed By: bgamari

Subscribers: ygale, rwbarton, thomie, carter

GHC Trac Issues: #15131

Differential Revision:
parent ca3d3039
......@@ -299,11 +299,27 @@ instance Foldable [] where
-- | @since
instance Foldable NonEmpty where
foldr f z ~(a :| as) = f a (List.foldr f z as)
foldl f z ~(a :| as) = List.foldl f (f z a) as
foldl1 f ~(a :| as) = List.foldl f a as
foldl f z (a :| as) = List.foldl f (f z a) as
foldl1 f (a :| as) = List.foldl f a as
-- GHC isn't clever enough to transform the default definition
-- into anything like this, so we'd end up shuffling a bunch of
-- Maybes around.
foldr1 f (p :| ps) = foldr go id ps p
go x r prev = f prev (r x)
-- We used to say
-- length (_ :| as) = 1 + length as
-- but the default definition is better, counting from 1.
-- The default definition also works great for null and foldl'.
-- As usual for cons lists, foldr' is basically hopeless.
foldMap f ~(a :| as) = f a `mappend` foldMap f as
fold ~(m :| ms) = m `mappend` fold ms
length (_ :| as) = 1 + List.length as
toList ~(a :| as) = a : as
-- | @since
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment