Convert seconds to compound duration: Difference between revisions
Content added Content deleted
(→JS ES6: Slightly less parochial assumptions about local labels) |
(→{{header|Haskell}}: Or, parameterising the local names for these durations:) |
||
Line 1,240: | Line 1,240: | ||
6000000 seconds = 9 wk, 6 d, 10 hr, 40 min |
6000000 seconds = 9 wk, 6 d, 10 hr, 40 min |
||
</pre> |
</pre> |
||
Or, parameterising the local names for these durations: |
|||
<lang haskell>import Data.List (intercalate) |
|||
timePhrase :: [String] -> Int -> String |
|||
timePhrase localNames secs = |
|||
intercalate ", " $ foldl timeTags [] $ zip (weekParts secs) localNames |
|||
where |
|||
timeTags :: [String] -> (Int, String) -> [String] |
|||
timeTags xs (n, s) |
|||
| n > 0 = xs ++ [show n ++ " " ++ s] |
|||
| otherwise = xs |
|||
weekParts :: Int -> [Int] |
|||
weekParts n = xs where |
|||
(xs, _) = foldl byUnits ([], n) [60, 60, 24, 7, 0] |
|||
byUnits :: ([Int], Int) -> Int -> ([Int], Int) |
|||
byUnits (parts, rest) x = |
|||
([m] ++ parts, quot (rest - m) u) where |
|||
(u, m) | x > 0 = (x, rem rest x) |
|||
| otherwise = (1, rest ) |
|||
-- TEST ---------------------------------------------------------------- |
|||
translation :: Int -> String |
|||
translation seconds = |
|||
show seconds ++ " -> " ++ |
|||
timePhrase ["wk", "d", "hr", "min", "sec"] seconds |
|||
main :: IO () |
|||
main = putStr $ intercalate "\n" $ |
|||
translation <$> [7259, 86400, 6000000]</lang> |
|||
{{Out}} |
|||
<pre>7259 -> 2 hr, 59 sec |
|||
86400 -> 1 d |
|||
6000000 -> 9 wk, 6 d, 10 hr, 40 min</pre> |
|||
=={{header|J}}== |
=={{header|J}}== |