From 6711a23f13f6aed1b22b2d456cdd56dcc247f4b3 Mon Sep 17 00:00:00 2001 From: meooow25 Date: Sun, 27 Oct 2024 00:02:34 +0530 Subject: [PATCH] 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. --- containers/changelog.md | 5 +++++ containers/src/Data/Graph.hs | 9 ++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/containers/changelog.md b/containers/changelog.md index 9ebc1dfe8..3eeee770f 100644 --- a/containers/changelog.md +++ b/containers/changelog.md @@ -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 diff --git a/containers/src/Data/Graph.hs b/containers/src/Data/Graph.hs index 7d6c96ad1..d06bc91ae 100644 --- a/containers/src/Data/Graph.hs +++ b/containers/src/Data/Graph.hs @@ -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 @@ -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. --