Jump to content

Ethiopian multiplication: Difference between revisions

m
(→‎Haskell :: Fold after unfold: Tidied and retitled)
Line 2,117:
Logging the stages of the '''unfoldr''' and '''foldr''' applications:
 
<lang haskell>import Data.BoolList (boolinits, intercalate, unfoldr)
import Data.List (intercalate, unfoldr)
import Data.Tuple (swap)
import Debug.Trace (trace)
Line 2,126 ⟶ 2,125:
ethMult :: Int -> Int -> Int
ethMult n m =
trace
let addedWhereOdd (d, x) a
(showDoubles pairs <> " |= 0" <> dshow =v (+)<> a x"\n")
)v
| otherwise = a
where
halved h
pairs = zip (unfoldr |halved 0n) <(iterate hdoubled =m)
doubled x = x + Just $x
halved traceh
| 0 < h (showHalf h)=
(swapJust $ quotRem h 2)
| otherwise = Nothingtrace
doubled x = x + x (showHalf h)
pairs = zip (unfoldr halved n) (iterateswap $ quotRem doubledh m2)
| otherwise = aNothing
in ( let x = foldr addedWhereOdd 0 pairs
v = foldr addedWhereOdd 0 in tracepairs
addedWhereOdd (d, showDoublesx) pairsa
| 0 < d = (+) a <> " = "x
| otherwise = <> show xa
<> "\n"
)
x
)
 
---------------------- TRACE DISPLAY ---------------------
 
showHalf :: Int -> String
showHalf x = "halve: " <> rjust 6 ' ' (show (quotRem x 2))
Line 2,155 ⟶ 2,151:
showDoubles xs =
"double:\n"
<> unlines (go <$> xs)
<> intercalate " + " (xs >>= fmapf)
where
( \x ->
go boolx
| 0 < fst x = "-> " <> (rjust 63 ' ' $ (show $ snd x)
| otherwise ("-> " <>= rjust 36 ' ' ($ show $ snd x))
f (0 < fstr, xq)
| 0 < r )= [show q]
| otherwise = xs[]
)
<> 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 -------------------------
9,659

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.