Skip to content

Commit 0ad89be

Browse files
committed
Refactor Ch4 largestSmallest using pattern matching to improve readability
Related purescript-contrib#340
1 parent 511dd50 commit 0ad89be

File tree

1 file changed

+10
-19
lines changed

1 file changed

+10
-19
lines changed

exercises/chapter4/test/no-peeking/Solutions.purs

+10-19
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,10 @@ module Test.NoPeeking.Solutions where
22

33
import Prelude
44
import Control.MonadZero (guard)
5-
import Data.Array (catMaybes, cons, filter, find, head, last, length, nub, null, tail, (..))
5+
import Data.Array (cons, filter, head, length, null, tail, (..), (:))
66
import Data.Foldable (foldl)
7-
import Data.Int (rem, quot)
8-
import Data.Maybe (Maybe(..), fromMaybe, maybe)
7+
import Data.Maybe (Maybe(..), fromMaybe)
98
import Data.Path (Path, filename, isDirectory, ls, size)
10-
import Data.String.Common (split)
11-
import Data.String.Pattern (Pattern(..))
129
import Data.Tuple (Tuple(..))
1310
import Test.Examples
1411

@@ -111,17 +108,11 @@ whereIs path fileName = head $ do
111108
pure path'
112109

113110
largestSmallest :: Path -> Array Path
114-
largestSmallest path =
115-
let files = onlyFiles path
116-
maybeSizes = map size files
117-
maybeMax = foldl (outlier (>)) Nothing maybeSizes
118-
maybeMin = foldl (outlier (<)) Nothing maybeSizes
119-
in catMaybes $ map (findFileBySize files) $ nub $ [maybeMax, maybeMin]
120-
where
121-
outlier :: (Int -> Int -> Boolean) -> Maybe Int -> Maybe Int -> Maybe Int
122-
outlier criteria Nothing Nothing = Nothing
123-
outlier criteria (Just x) Nothing = Just x
124-
outlier criteria Nothing (Just x) = Just x
125-
outlier criteria (Just x1) (Just x2) = if criteria x1 x2 then Just x1 else Just x2
126-
findFileBySize :: Array Path -> Maybe Int -> Maybe Path
127-
findFileBySize files maybeSize = find (\file -> size file == maybeSize) files
111+
largestSmallest path = foldl loop [] (onlyFiles path) where
112+
loop :: Array Path -> Path -> Array Path
113+
loop [largest, smallest] current | size current < size smallest = [largest, current]
114+
| size current > size largest = [current, smallest]
115+
| otherwise = [largest, smallest]
116+
loop [last] current | size current < size last = [current, last]
117+
| otherwise = [last, current]
118+
loop arr current = current : arr

0 commit comments

Comments
 (0)