Middle three digits: Difference between revisions

Content deleted Content added
Hout (talk | contribs)
m →‎{{header|JavaScript}}: (simpler expression for max numeric string length)
Hout (talk | contribs)
m →‎{{header|Haskell}}: (Aligned the output cols for easier reading)
Line 2,452:
mid3 n
| m < 100 = Left "is too small"
| even llng = Left "has an even number of digits"
| otherwise = Right . take 3 $ drop ((llng - 3) `div` 2) s
where
m = abs n
s = show m
llng = length s
 
showMid3 :: Int -> String
showMid3 n = show n ++ ": " ++ either id id (mid3 n)
 
-- TEST --------------------------------------------------------
main :: IO ()
main = do
let xs =
mapM_
(putStrLn . showMid3) [ 123
[ 123 , 12345
, 123451234567
, 1234567987654321
, 98765432110001
, -10001
, -10001123
, -123100
, -100
, 100-12345
, -123451
, 12
, 2-1
, -110
, -102002
, -2002
, -20020
, 0 ]
w = maximum $ (length . show) <$> xs
]</lang>
(putStrLn . unlines) $
]</lang(\n ->
justifyRight w ' ' (show n) ++
" -> " ++ either ((>>= id) . ("(" :) . (: [")"])) id (mid3 n)) <$>
xs
where
justifyRight :: Int -> Char -> String -> String
justifyRight n c s = drop (length s) (replicate n c ++ s)</lang>
Output:
<pre> 123: -> 123
12345: -> 234
1234567: -> 345
987654321: -> 654
10001: -> 000
-10001: -> 000
-123: -> 123
-100: -> 100
100: -> 100
-12345: -> 234
1: -> (is too small)
2: -> (is too small)
-1: -> (is too small)
-10: -> (is too small)
2002: -> (has an even number of digits)
-2002: -> (has an even number of digits)
0: -> (is too small)</pre>
 
=={{header|Icon}} and {{header|Unicon}}==