From d64c53d0517d59db51543d78c9148a5260ceccfe Mon Sep 17 00:00:00 2001 From: Profpatsch Date: Thu, 6 Mar 2025 23:58:12 +0100 Subject: [PATCH] feat(users/Profpatsch/my-prelude): add RevList Change-Id: Icb98c6ec77a305f44149f344dccbf3969a83951a Reviewed-on: https://cl.tvl.fyi/c/depot/+/13210 Tested-by: BuildkiteCI Reviewed-by: Profpatsch --- users/Profpatsch/my-prelude/default.nix | 1 + users/Profpatsch/my-prelude/my-prelude.cabal | 1 + users/Profpatsch/my-prelude/src/RevList.hs | 28 ++++++++++++++++++++ 3 files changed, 30 insertions(+) create mode 100644 users/Profpatsch/my-prelude/src/RevList.hs diff --git a/users/Profpatsch/my-prelude/default.nix b/users/Profpatsch/my-prelude/default.nix index c739676c1..7755943c4 100644 --- a/users/Profpatsch/my-prelude/default.nix +++ b/users/Profpatsch/my-prelude/default.nix @@ -19,6 +19,7 @@ pkgs.haskellPackages.mkDerivation { ./src/Test.hs ./src/Parse.hs ./src/Pretty.hs + ./src/RevList.hs ./src/Seconds.hs ./src/Tool.hs ./src/ValidationParseT.hs diff --git a/users/Profpatsch/my-prelude/my-prelude.cabal b/users/Profpatsch/my-prelude/my-prelude.cabal index dba092fda..b4dd64668 100644 --- a/users/Profpatsch/my-prelude/my-prelude.cabal +++ b/users/Profpatsch/my-prelude/my-prelude.cabal @@ -70,6 +70,7 @@ library Test Postgres.Decoder Postgres.MonadPostgres + RevList ValidationParseT Parse Pretty diff --git a/users/Profpatsch/my-prelude/src/RevList.hs b/users/Profpatsch/my-prelude/src/RevList.hs new file mode 100644 index 000000000..0f002c07e --- /dev/null +++ b/users/Profpatsch/my-prelude/src/RevList.hs @@ -0,0 +1,28 @@ +module RevList where + +import Data.Semigroup qualified as Semigroup +import PossehlAnalyticsPrelude + +-- | A reversed list; `:` adds to the end of the list, and '(<>)' is reversed (i.e. @longList <> [oneElement]@ will be O(1) instead of O(n)) +-- +-- Invariant: the inner list is already reversed. +newtype RevList a = RevList [a] + deriving stock (Eq) + deriving (Semigroup, Monoid) via (Semigroup.Dual [a]) + +empty :: RevList a +empty = RevList [] + +singleton :: a -> RevList a +singleton a = RevList [a] + +-- | (@O(n)@) Turn the list into a reversed list (by reversing) +revList :: [a] -> RevList a +revList xs = RevList $ reverse xs + +-- | (@O(n)@) Turn the reversed list into a list (by reversing) +revListToList :: RevList a -> [a] +revListToList (RevList rev) = reverse rev + +instance (Show a) => Show (RevList a) where + show (RevList rev) = rev & show