Middle three digits: Difference between revisions
Content added Content deleted
m (→{{header|JavaScript}}: (simpler expression for max numeric string length)) |
m (→{{header|Haskell}}: (Aligned the output cols for easier reading)) |
||
Line 2,452: | Line 2,452: | ||
mid3 n |
mid3 n |
||
| m < 100 = Left "is too small" |
| m < 100 = Left "is too small" |
||
| even |
| even lng = Left "has an even number of digits" |
||
| otherwise = Right . take 3 $ drop (( |
| otherwise = Right . take 3 $ drop ((lng - 3) `div` 2) s |
||
where |
where |
||
m = abs n |
m = abs n |
||
s = show m |
s = show m |
||
lng = length s |
|||
showMid3 :: Int -> String |
|||
showMid3 n = show n ++ ": " ++ either id id (mid3 n) |
|||
-- TEST -------------------------------------------------------- |
|||
main :: IO () |
main :: IO () |
||
main = |
main = do |
||
let xs = |
|||
mapM_ |
|||
[ 123 |
|||
, 12345 |
|||
, |
, 1234567 |
||
, |
, 987654321 |
||
, |
, 10001 |
||
, 10001 |
, -10001 |
||
, - |
, -123 |
||
, - |
, -100 |
||
, |
, 100 |
||
, |
, -12345 |
||
, |
, 1 |
||
, |
, 2 |
||
, |
, -1 |
||
, - |
, -10 |
||
, |
, 2002 |
||
, 2002 |
, -2002 |
||
, |
, 0 |
||
] |
|||
w = maximum $ (length . show) <$> xs |
|||
⚫ | |||
(putStrLn . unlines) $ |
|||
⚫ | |||
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: |
Output: |
||
<pre>123 |
<pre> 123 -> 123 |
||
12345 |
12345 -> 234 |
||
1234567 |
1234567 -> 345 |
||
987654321 |
987654321 -> 654 |
||
10001 |
10001 -> 000 |
||
-10001 |
-10001 -> 000 |
||
-123 |
-123 -> 123 |
||
-100 |
-100 -> 100 |
||
100 |
100 -> 100 |
||
-12345 |
-12345 -> 234 |
||
1 |
1 -> (is too small) |
||
2 |
2 -> (is too small) |
||
-1 |
-1 -> (is too small) |
||
-10 |
-10 -> (is too small) |
||
2002 |
2002 -> (has an even number of digits) |
||
-2002 |
-2002 -> (has an even number of digits) |
||
0 |
0 -> (is too small)</pre> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |