Ethiopian multiplication: Difference between revisions
Content added Content deleted
m (→Haskell :: Fold after unfold: (Tidied)) |
|||
Line 2,209: | Line 2,209: | ||
This additional generality means that our '''ethMult''' function can now replicate a string n times as readily as it multiplies an integer n times, or raises an integer to the nth power. |
This additional generality means that our '''ethMult''' function can now replicate a string n times as readily as it multiplies an integer n times, or raises an integer to the nth power. |
||
<lang haskell>import |
<lang haskell>import Control.Monad (join) |
||
import Control.Monad (join) |
|||
import Data.List (unfoldr) |
import Data.List (unfoldr) |
||
import Data.Monoid (getProduct, getSum) |
|||
import Data.Tuple (swap) |
import Data.Tuple (swap) |
||
----------------- ETHIOPIAN MULTIPLICATION --------------- |
----------------- ETHIOPIAN MULTIPLICATION --------------- |
||
ethMult |
ethMult :: |
||
(Monoid m) => |
|||
Int -> |
|||
m -> |
|||
m |
|||
ethMult n m = |
ethMult n m = |
||
foldr addedWhereOdd mempty $ |
foldr addedWhereOdd mempty $ |
||
zip (unfoldr half n) $ iterate (join (<>)) m |
|||
where |
where |
||
half n |
half n |
||
Line 2,232: | Line 2,235: | ||
main = do |
main = do |
||
mapM_ print $ |
mapM_ print $ |
||
[ getSum $ ethMult 17 34 -- 34 * 17 |
[ getSum $ ethMult 17 34, -- 34 * 17 |
||
getProduct $ ethMult 3 34 -- 34 ^ 3 |
|||
] |
] |
||
-- [3 ^ 17, 4 ^ 17] |
|||
<> (getProduct <$> ([ethMult 17] <*> [3, 4])) |
|||
print $ ethMult 17 "34" |
print $ ethMult 17 "34" |
||
print $ ethMult 17 [3, 4]</lang> |
print $ ethMult 17 [3, 4]</lang> |