Ethiopian multiplication: Difference between revisions

m (→‎{{header|Phix}}: added syntax colouring the hard way)
(→‎Haskell :: Fold after unfold: Tidied and retitled)
Line 2,113:
 
 
===Fold after unfold===
Or, as an unfold followed by a refold:
 
Logging the stages of the '''unfoldr''' and '''foldr''' applications:
<lang haskell>import Data.List (intercalate, unfoldr)
 
import Debug.Trace (trace)
<lang haskell>import Data.Bool (bool)
<lang haskell>import Data.List (intercalate, unfoldr)
import Data.Tuple (swap)
import DataDebug.BoolTrace (booltrace)
 
-- ETHIOPIAN MULTIPLICATION ---------------- ETHIOPIAN MULTIPLICATION ---------------
 
ethMult :: Int -> Int -> Int
Line 2,128 ⟶ 2,130:
| otherwise = a
halved h
| 0 < h = Just $ trace (showHalf h) (swap $ quotRem h 2)
Just $
trace
(showHalf h)
(swap $ quotRem h 2)
| otherwise = Nothing
doubled x = x + x
pairs = zip (unfoldr halved n) (iterate doubled m)
in ( let x = foldr addedWhereOdd 0 pairs
in trace
in trace (showDoubles pairs ++ " = " ++ show x ++ "\n") x)
( showDoubles pairs
 
<> " = "
-- TRACE DISPLAY -------------------------------------------
<> show x
<> "\n"
)
x
)
 
-- TRACE DISPLAY ---------------------- TRACE DISPLAY ---------------------
showHalf :: Int -> String
showHalf x = "halve: " ++<> rjust 6 ' ' (show (quotRem x 2))
 
showDoubles :: [(Int, Int)] -> String
showDoubles xs =
"double:\n" ++
<> unlines
( fmap
( \x ->
bool
(rjust 6 ' ' $ show $ snd x)
("-> " ++<> rjust 3 ' ' (show $ snd x))
(0 < fst x))
xs) ++ )
xs
intercalate " + " (xs >>= (\(r, q) -> bool [] [show q] (0 < r)))
)
<> intercalate
" + "
intercalate " + " (xs >>= (\(r, q) -> bool [] [show q] (0 < r)))
 
rjust :: Int -> Char -> String -> String
rjust n c s = drop (length s) (replicate n c ++<> s)
 
-- TEST -------------------------- TEST -------------------------
main :: IO ()
main = do
9,655

edits