Skip to content

Commit

Permalink
Implement toList and toNonEmpty for SCC (#1057)
Browse files Browse the repository at this point in the history
The default implementations perform an avoidable list copy for
NECyclicSCC. Also fix flattenSCC being made too lazy accidentally in a
previous commit.
  • Loading branch information
meooow25 authored Oct 27, 2024
1 parent d2a508a commit 9a9e210
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
5 changes: 5 additions & 0 deletions containers/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@

* Add `foldMap` for `Data.IntSet`. (Soumik Sarkar)

### Performance improvements

* For `Data.Graph.SCC`, `Foldable.toList` and `Foldable1.toNonEmpty` now
do not perform a copy. (Soumik Sarkar)

## Unreleased with `@since` annotation for 0.7.1:

### Additions
Expand Down
9 changes: 8 additions & 1 deletion containers/src/Data/Graph.hs
Original file line number Diff line number Diff line change
Expand Up @@ -220,11 +220,16 @@ instance F.Foldable SCC where
foldr c n (AcyclicSCC v) = c v n
foldr c n (NECyclicSCC vs) = foldr c n vs

toList = flattenSCC

#if MIN_VERSION_base(4,18,0)
-- | @since 0.7.0
instance F1.Foldable1 SCC where
foldMap1 f (AcyclicSCC v) = f v
foldMap1 f (NECyclicSCC vs) = F1.foldMap1 f vs

toNonEmpty = flattenSCC1

-- TODO define more methods
#endif

Expand Down Expand Up @@ -258,7 +263,9 @@ flattenSCCs = concatMap flattenSCC
-- This function is retained for backward compatibility,
-- 'flattenSCC1' has the more precise type.
flattenSCC :: SCC vertex -> [vertex]
flattenSCC = NE.toList . flattenSCC1
flattenSCC (AcyclicSCC v) = [v]
flattenSCC (NECyclicSCC (v :| vs)) = v : vs
-- Note: Best to avoid NE.toList, it is too lazy.

-- | The vertices of a strongly connected component.
--
Expand Down

0 comments on commit 9a9e210

Please sign in to comment.