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

power: slight optimization #40

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions src/Data/Monoid.purs
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,19 @@ instance monoidArray :: Monoid (Array a) where
-- | For that, we would additionally need the ability to invert elements, i.e.
-- | a Group.
power :: forall m. Monoid m => m -> Int -> m
power x = go
power x p
| p <= 0 = mempty
| otherwise = go p
where
-- optimize dictionary lookup
append :: m -> m -> m
append = (<>)

go :: Int -> m
go p
| p <= 0 = mempty
| p == 1 = x
| p `mod` 2 == 0 = let x' = go (p/2) in x' <> x'
| otherwise = let x' = go (p/2) in x' <> x' <> x
go p'
| p' `mod` 2 == 0 = let x' = go (p'/2) in x' `append` x'
| p' == 1 = x
| otherwise = let x' = go (p'/2) in x' `append` x' `append` x

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