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

Commit a5efd76

Browse files
committed
power: slight optimization
1 parent 4df49ec commit a5efd76

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/Data/Monoid.purs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,14 +47,19 @@ instance monoidArray :: Monoid (Array a) where
4747
-- | For that, we would additionally need the ability to invert elements, i.e.
4848
-- | a Group.
4949
power :: forall m. Monoid m => m -> Int -> m
50-
power x = go
50+
power x p
51+
| p <= 0 = mempty
52+
| otherwise = go p
5153
where
54+
-- optimize dictionary lookup
55+
append :: m -> m -> m
56+
append = (<>)
57+
5258
go :: Int -> m
53-
go p
54-
| p <= 0 = mempty
55-
| p == 1 = x
56-
| p `mod` 2 == 0 = let x' = go (p/2) in x' <> x'
57-
| otherwise = let x' = go (p/2) in x' <> x' <> x
59+
go p'
60+
| p' `mod` 2 == 0 = let x' = go (p'/2) in x' `append` x'
61+
| p' == 1 = x
62+
| otherwise = let x' = go (p'/2) in x' `append` x' `append` x
5863

5964
-- | Allow or "truncate" a Monoid to its `mempty` value based on a condition.
6065
guard :: forall m. Monoid m => Boolean -> m -> m

0 commit comments

Comments
 (0)