Multiplication tables: Difference between revisions

→‎{{header|Haskell}}: Simplified the first version, disentangled model from display, updated output
(→‎{{header|Haskell}}: Simplified the first version, disentangled model from display, updated output)
Line 2,580:
 
=={{header|Haskell}}==
<lang haskell>import Data.ListMaybe (intercalatefromMaybe, transposemaybe)
import Data.Monoid ((<>))
import Data.Bool (bool)
 
mulTabletable :: [Int] -> [[StringMaybe Int]]
mulTabletable nxs =
let xsaxis = [1Just ..<$> n]xs
in xs(Nothing >>=: axis) :
zipWith
\x -> [show x <> ":" : (xs >>= \y -> [bool (show (x * y)) mempty (y < x)])]
(:)
 
axis
table :: String -> [[String]] -> [String]
(xs >>=
table gap rows =
\x ->
let justifyRight c n s = drop (length s) (replicate n c <> s)
[ xs >>=
in intercalate gap <$>
transpose \y ->
((fmap =<< justifyRight ' ' . maximum . fmap length)if <$>x transpose> rows)y
then [Nothing]
else [Just (x * y)]
])
 
-- TEST ---------------------------------------------------
main :: IO ()
main = do
main = (putStrLn . unlines . table " " . mulTable) 12</lang>
putStrLn $ showTable $ table [5 .. 10]
putStrLn $ showTable $ table [1 .. 12]
putStrLn $ showTable $ table [95 .. 100]
 
-- FORMATTING ---------------------------------------------
showTable :: [[Maybe Int]] -> String
showTable xs =
let w = 1 + (length . show) (fromMaybe 0 $ (last . last) xs)
gap = replicate w ' '
rows = (maybe gap (rjust w ' ' . show) =<<) <$> xs
in unlines $ head rows : [] : tail rows
 
tablerjust :: StringInt -> Char -> [[String]] -> [String]
rjust let justifyRightn c n s = (drop (. length s) <*> (replicate n c ++)</lang> s)
{{Out}}
<pre> 1: 1 2 3 4 5 6 7 8 9 10 11 12
 
2: 4 6 8 10 12 14 16 18 20 22 24
3: 5 25 30 9 12 15 18 21 24 27 3035 40 33 45 3650
4: 6 16 20 24 28 32 36 42 40 48 4454 4860
5: 7 49 2556 3063 35 40 45 50 55 6070
6: 8 64 3672 42 48 54 60 66 7280
7: 9 81 49 56 63 70 77 8490
8: 10 64 72 80 88 96100
 
9: 81 90 99 108
10: 1 2 3 4 5 6 7 8 9 10 100 11011 12012
 
11: 121 132
12: 1 1 2 3 4 5 6 7 8 9 10 11 144</pre>12
2: 4 6 8 10 12 14 16 18 20 22 24
3 9 12 15 18 21 24 27 30 33 36
4 16 20 24 28 32 36 40 44 48
5 25 30 35 40 45 50 55 60
6 36 42 48 54 60 66 72
7 49 56 63 70 77 84
8 64 72 80 88 96
9: 81 9081 90 99 99 108
10 100 110 120
11: 121 121 132
12 144
 
95 96 97 98 99 100
 
95 9025 9120 9215 9310 9405 9500
96 9216 9312 9408 9504 9600
97 9409 9506 9603 9700
98 9604 9702 9800
99 9801 9900
100 10000</pre>
 
Or, more roughly and directly:
9,659

edits