Convert seconds to compound duration: Difference between revisions

Content added Content deleted
m (→‎{{header|Haskell}}: simplified)
Line 152: Line 152:
=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Control.Monad (forM_)
<lang haskell>import Control.Monad (forM_)
import Data.List (intercalate)
import Data.List (intercalate, mapAccumR)
import System.Environment (getArgs)
import System.Environment (getArgs)
import Text.Printf (printf)
import Text.Printf (printf)
Line 158: Line 158:


reduceBy :: Integral a => a -> [a] -> [a]
reduceBy :: Integral a => a -> [a] -> [a]
n `reduceBy` [] = [n]
n `reduceBy` xs = n' : ys where (n', ys) = mapAccumR quotRem n xs
n `reduceBy` (d:ds) = let (q, r) = n `quotRem` d in q : r `reduceBy` ds


-- Duration/label pairs.
-- Duration/label pairs.
durLabs :: [(Integer, String)]
durLabs :: [(Integer, String)]
durLabs = [(1, "wk"), (7, "d"), (24, "hr"), (60, "min"), (60, "sec")]
durLabs = [(undefined, "wk"), (7, "d"), (24, "hr"), (60, "min"), (60, "sec")]


-- Time broken down into non-zero durations and their labels.
-- Time broken down into non-zero durations and their labels.
compdurs :: Integer -> [(Integer, String)]
compdurs :: Integer -> [(Integer, String)]
compdurs t = let ds = t `reduceBy` scanr1 (*) (map fst $ tail durLabs)
compdurs t = let ds = t `reduceBy` (map fst $ tail durLabs)
in filter ((/=0) . fst) $ zip ds (map snd durLabs)
in filter ((/=0) . fst) $ zip ds (map snd durLabs)