Convert seconds to compound duration: Difference between revisions

Content added Content deleted
m (→‎{{header|Haskell}}: Tidied parameterised variant.)
(simplify, make clear that helper functions aren't closures)
Line 3,500: Line 3,500:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun compoundDuration seconds =
<lang sml>local
fun fmtNonZero (0, _, list) = list
let
fun fmtNonZero (0, s) = NONE
| fmtNonZero (n, s, list) = Int.toString n ^ " " ^ s :: list
fun divModHead (_, []) = []
| fmtNonZero (x, s) = SOME (Int.toString x ^ " " ^ s)
| divModHead (d, head :: tail) = head div d :: head mod d :: tail

in
fun divMod (divisor, (duration, list)) =
fun compoundDuration seconds =
(duration div divisor, duration mod divisor :: list)
let

val (weeks, subUnits) = foldl divMod (seconds, []) [60, 60, 24, 7]
val digits = foldl divModHead [seconds] [60, 60, 24, 7]
and units = ["wk", "d", "hr", "min", "sec"]
in
in
(String.concatWith ", "
o List.mapPartial fmtNonZero
String.concatWith ", " (ListPair.foldr fmtNonZero [] (digits, units))
end
o ListPair.zip) (weeks :: subUnits, ["wk", "d", "hr", "min", "sec"])
end
end


val () = app (fn s => print (compoundDuration s ^ "\n")) [7259, 86400, 6000000]</lang>
val () = app (fn s => print (compoundDuration s ^ "\n")) [7259, 86400, 6000000]</lang>