Skip to content
This repository was archived by the owner on Oct 4, 2020. It is now read-only.

Commit 0e44e99

Browse files
no-longer-on-githu-bpaf31
authored andcommitted
Make findMin and findMax tail-recursive (#122)
1 parent e6cf057 commit 0e44e99

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

src/Data/Map.purs

+10-6
Original file line numberDiff line numberDiff line change
@@ -246,15 +246,19 @@ lookupGT k = go
246246

247247
-- | Returns the pair with the greatest key
248248
findMax :: forall k v. Map k v -> Maybe { key :: k, value :: v }
249-
findMax Leaf = Nothing
250-
findMax (Two _ k1 v1 right) = Just $ fromMaybe { key: k1, value: v1 } $ findMax right
251-
findMax (Three _ _ _ _ k2 v2 right) = Just $ fromMaybe { key: k2, value: v2 } $ findMax right
249+
findMax = go Nothing
250+
where
251+
go acc Leaf = acc
252+
go _ (Two _ k1 v1 right) = go (Just { key: k1, value: v1 }) right
253+
go _ (Three _ _ _ _ k2 v2 right) = go (Just { key: k2, value: v2 }) right
252254

253255
-- | Returns the pair with the least key
254256
findMin :: forall k v. Map k v -> Maybe { key :: k, value :: v }
255-
findMin Leaf = Nothing
256-
findMin (Two left k1 v1 _) = Just $ fromMaybe { key: k1, value: v1 } $ findMin left
257-
findMin (Three left k1 v1 _ _ _ _) = Just $ fromMaybe { key: k1, value: v1 } $ findMin left
257+
findMin = go Nothing
258+
where
259+
go acc Leaf = acc
260+
go _ (Two left k1 v1 _) = go (Just { key: k1, value: v1 }) left
261+
go _ (Three left k1 v1 _ _ _ _) = go (Just { key: k1, value: v1 }) left
258262

259263
-- | Fold over the entries of a given map where the key is between a lower and
260264
-- | an upper bound. Passing `Nothing` as either the lower or upper bound

0 commit comments

Comments
 (0)