Multiplication tables: Difference between revisions

m
(→‎{{header|Haskell}}: Switched core type from [Int] to Maybe Int)
Line 2,242:
 
=={{header|Haskell}}==
<lang haskell>importmultTable Control.Monad:: Int -> [[Maybe Int]]
multTable n =
import Text.Printf
(\x ->
 
Just x :
main = do
fmt Nothing = pad:
putStrLn $ " x" ++ concatMap fmt [1..12]
((\y ->
zipWithM_ f [1..12] $ iterate (" " ++) ""
if sy =< show nx
where f n s = putStrLn $ fmt n ++ s ++ concatMap (fmt . (*n)) [n..12]
fmt n = printf "%4d" (nthen :: Int)</lang>Nothing
(\y -> if y < x then Nothing else Just (x * y)) <$>
 
where range)) = [1..n]<$>
 
<$> 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 tbl = unlines $ (concat . (fmt <$>)) <$> tbl
where
unlines $ (concat . (fmt <$>)) <$> tbl
pad = " "
fmt Nothing = pad
fmt (Just n) = drop (length s) (pad ++ s)
where
pad s = " show "n
fmt Nothing = pad
fmt (Just n) = drop (length s) (pad ++ s)
where
s = show n
 
main :: IO ()
9,659

edits