Skip to content

Instantly share code, notes, and snippets.

@amalloy
Created April 17, 2019 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amalloy/a6664c0f4187fcb946e44774cf95468c to your computer and use it in GitHub Desktop.
Save amalloy/a6664c0f4187fcb946e44774cf95468c to your computer and use it in GitHub Desktop.
import Data.Semigroup (stimes)
newtype Product = Product Integer
instance Semigroup Product where
Product x <> Product y = Product $ x * y
instance Monoid Product where
mempty = Product 1
-- Implementing exponentiation by hand with N multiplications
-- *Main> let (Product x) = iterate (<> Product 2) (Product 2) !! 1000000 in x `mod` 10
-- 2 (very slowly)
-- Letting Haskell do it in log(N) multiplications via repeated squaring
-- *Main> let (Product x) = stimes 10000001 (Product 2) in x `mod` 10
-- 2 (very quickly)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment