Multiplication tables: Difference between revisions

Content added Content deleted
m (→‎{{header|Haskell}}: Tidied, removed one import.)
Line 3,517: Line 3,517:
=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.Maybe (fromMaybe, maybe)
<lang haskell>import Data.Maybe (fromMaybe, maybe)
import Data.Bool (bool)


------------------- MULTIPLICATION TABLE -----------------
table :: [Int] -> [[Maybe Int]]

table xs =
mulTable :: [Int] -> [[Maybe Int]]
mulTable xs =
(Nothing : axis) :
(Nothing : axis) :
zipWith
zipWith
(:)
(:)
axis
axis
[ [ bool (Just (x * y)) Nothing (x > y)
[[upperMul x y | y <- xs] | x <- xs]
| y <- xs ]
| x <- xs ]
where
where
axis = Just <$> xs
axis = Just <$> xs
upperMul x y
| x > y = Nothing
| otherwise = Just (x * y)



--------------------------- TEST ---------------------------
--------------------------- TEST -------------------------
main :: IO ()
main :: IO ()
main =
main =
(putStrLn . unlines) $
(putStrLn . unlines) $
showTable . mulTable
showTable . table <$> [[13 .. 20], [1 .. 12], [95 .. 100]]
<$> [ [13 .. 20],
[1 .. 12],
[95 .. 100]
]


------------------------ FORMATTING ------------------------
------------------------ FORMATTING ----------------------
showTable :: [[Maybe Int]] -> String
showTable :: [[Maybe Int]] -> String
showTable xs = unlines $ head rows : [] : tail rows
showTable xs = unlines $ head rows : [] : tail rows
Line 3,544: Line 3,551:
gap = replicate w ' '
gap = replicate w ' '
rows = (maybe gap (rjust w ' ' . show) =<<) <$> xs
rows = (maybe gap (rjust w ' ' . show) =<<) <$> xs
rjust n c = (drop . length) <*> (replicate n c <>)</lang>

rjust :: Int -> Char -> String -> String
rjust n c = (drop . length) <*> (replicate n c ++)</lang>
{{Out}}
{{Out}}
<pre> 13 14 15 16 17 18 19 20
<pre> 13 14 15 16 17 18 19 20