Multiplication tables: Difference between revisions

Content added Content deleted
Line 2,814: Line 2,814:
table :: [Int] -> [[Maybe Int]]
table :: [Int] -> [[Maybe Int]]
table xs =
table xs =
let axis = Just <$> xs
(Nothing : axis) :
zipWith
in (Nothing : axis) :
zipWith
(:)
(:)
axis
[ [ bool (Just (x * y)) Nothing (x > y)
axis
[ [ bool (Just (x * y)) Nothing (x > y)
| y <- xs ]
| y <- xs ]
| x <- xs ]
where
| x <- xs ]
axis = Just <$> xs


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


-- FORMATTING ---------------------------------------------
------------------------ FORMATTING ------------------------
showTable :: [[Maybe Int]] -> String
showTable :: [[Maybe Int]] -> String
showTable xs =
showTable xs = unlines $ head rows : [] : tail rows
where
let w = 1 + (length . show) (fromMaybe 0 $ (last . last) xs)
w = 1 + (length . show) (fromMaybe 0 $ (last . last) xs)
gap = replicate w ' '
rows = (maybe gap (rjust w ' ' . show) =<<) <$> xs
gap = replicate w ' '
rows = (maybe gap (rjust w ' ' . show) =<<) <$> xs
in unlines $ head rows : [] : tail rows


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