Multiplication tables: Difference between revisions

Content added Content deleted
(→‎{{header|Haskell}}: Switched core type from [Int] to Maybe Int)
Line 2,242: Line 2,242:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Control.Monad
<lang haskell>multTable :: Int -> [[Maybe Int]]
multTable n =
import Text.Printf
(\x ->

Just x :
main = do
Nothing :
putStrLn $ " x" ++ concatMap fmt [1..12]
((\y ->
zipWithM_ f [1..12] $ iterate (" " ++) ""
if y < x
where f n s = putStrLn $ fmt n ++ s ++ concatMap (fmt . (*n)) [n..12]
fmt n = printf "%4d" (n :: Int)</lang>
then Nothing
else Just (x * y)) <$>

range)) <$>

range
Or, making do without imports beyond the Prelude, and separating data from formatting:
where

range = [1 .. n]
<lang Haskell>multTable :: Int -> [[Maybe Int]]
multTable n =
(\x -> Just x : Nothing : (
(\y -> if y < x then Nothing else Just (x * y))
<$> range))
<$> range
where range = [1..n]


tableString :: [[Maybe Int]] -> String
tableString :: [[Maybe Int]] -> String
tableString tbl =
tableString tbl = unlines $ (concat . (fmt <$>)) <$> tbl
where
unlines $ (concat . (fmt <$>)) <$> tbl
pad = " "
fmt Nothing = pad
fmt (Just n) = drop (length s) (pad ++ s)
where
where
pad = " "
s = show n
fmt Nothing = pad
fmt (Just n) = drop (length s) (pad ++ s)
where
s = show n


main :: IO ()
main :: IO ()