Skip to content

Commit 6711a23

Browse files
committed
Implement toList and toNonEmpty for SCC
The default implementations perform an avoidable list copy for NECyclicSCC. Also fix flattenSCC being made too lazy accidentally in a previous commit.
1 parent d2a508a commit 6711a23

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

containers/changelog.md

+5
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@
5353

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

56+
### Performance improvements
57+
58+
* For `Data.Graph.SCC`, `Foldable.toList` and `Foldable1.toNonEmpty` now
59+
do not perform a copy. (Soumik Sarkar)
60+
5661
## Unreleased with `@since` annotation for 0.7.1:
5762

5863
### Additions

containers/src/Data/Graph.hs

+8-1
Original file line numberDiff line numberDiff line change
@@ -220,11 +220,16 @@ instance F.Foldable SCC where
220220
foldr c n (AcyclicSCC v) = c v n
221221
foldr c n (NECyclicSCC vs) = foldr c n vs
222222

223+
toList = flattenSCC
224+
223225
#if MIN_VERSION_base(4,18,0)
224226
-- | @since 0.7.0
225227
instance F1.Foldable1 SCC where
226228
foldMap1 f (AcyclicSCC v) = f v
227229
foldMap1 f (NECyclicSCC vs) = F1.foldMap1 f vs
230+
231+
toNonEmpty = flattenSCC1
232+
228233
-- TODO define more methods
229234
#endif
230235

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

263270
-- | The vertices of a strongly connected component.
264271
--

0 commit comments

Comments
 (0)