From 447943f401c2517511e62835098589e41be7cc6c Mon Sep 17 00:00:00 2001 From: Joshua Clayton Date: Sat, 30 Apr 2016 07:54:06 -0400 Subject: [PATCH] Extract aggregate data structure --- app/Main.hs | 3 +-- src/Unused/Types.hs | 33 ++++++++++++++++++++++++++------- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/app/Main.hs b/app/Main.hs index 6b58596..398ee85 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -4,7 +4,6 @@ import System.Console.ANSI import Unused.TermSearch (search) import Unused.Parser (parseLines) import Unused.Types -import Data.Map.Strict (toList) main :: IO () main = do @@ -14,7 +13,7 @@ main = do case withOneOccurrence $ withOneFile response of Right termMatchSet -> - mapM_ printMatchPair $ toList termMatchSet + mapM_ printMatchPair $ listFromMatchSet termMatchSet Left e -> do setSGR [SetColor Background Vivid Red] setSGR [SetColor Foreground Vivid White] diff --git a/src/Unused/Types.hs b/src/Unused/Types.hs index 7dcd690..013f2e7 100644 --- a/src/Unused/Types.hs +++ b/src/Unused/Types.hs @@ -3,11 +3,13 @@ module Unused.Types , TermMatchSet , ParseResponse(..) , responseFromParse + , listFromMatchSet , withOneFile , withOneOccurrence ) where import Text.Parsec (ParseError) +import Data.Bifunctor (second) import qualified Data.Map.Strict as Map import Data.List (isInfixOf) import Unused.Util (groupBy) @@ -18,20 +20,37 @@ data TermMatch = TermMatch , occurrences :: Int } deriving Show -type TermMatchSet = Map.Map String [TermMatch] +data TermResults = TermResults + { matches :: [TermMatch] + , totalFiles :: Int + , totalOccurrences :: Int + } + +type TermMatchSet = Map.Map String TermResults type ParseResponse = Either ParseError TermMatchSet +resultsFromMatches :: [TermMatch] -> TermResults +resultsFromMatches m = + TermResults + { matches = m + , totalFiles = totalFiles' + , totalOccurrences = totalOccurrences' + } + where + totalFiles' = length m + totalOccurrences' = sum $ fmap occurrences m + responseFromParse :: Either ParseError [TermMatch] -> ParseResponse responseFromParse = - fmap $ Map.fromList . groupBy term + fmap $ Map.fromList . map (second resultsFromMatches) . groupBy term withOneFile :: ParseResponse -> ParseResponse -withOneFile = fmap $ Map.filterWithKey (\_ a -> length a == 1) +withOneFile = fmap $ Map.filterWithKey (\_ a -> totalFiles a == 1) withOneOccurrence :: ParseResponse -> ParseResponse -withOneOccurrence = fmap $ Map.filterWithKey (\_ a -> (sum $ fmap occurrences a) == 1) +withOneOccurrence = fmap $ Map.filterWithKey (\_ a -> totalOccurrences a == 1) -notMatchingPath :: String -> ParseResponse -> ParseResponse -notMatchingPath s = - fmap $ Map.map $ filter (not . isInfixOf s . path) +listFromMatchSet :: TermMatchSet -> [(String, [TermMatch])] +listFromMatchSet = + map (second matches) . Map.toList