I have a function timeToMinutes
that takes a 24-hour time as a string argument (in digital clock format, e.g., "15:47") and converts it to the number of minutes past the last midnight. For instance, timeToMinutes["3:45"]
yields 225
.
Here is the function as I have written it:
timeToMinutes[time_] :=
Function[pair, 60*pair[[1]] + pair[[2]]]@(ToExpression /@ time~StringSplit~":");
First it splits the string at the colon, then converts the two resultant strings to a pair of expressions, then sums 60 times the first member of the pair and one times the second member of the pair. This works fine, but I would like to rewrite it using pattern matching. What I have in mind is something like:
newTimeToMinutes = Function[time:(ToString[hours_]~~":"~~ToString[mins_]), 60*hours + mins]
The argument time
would be dissected into the two numbers on either side of the colon, furthermore, the numbers on either side of the colon would be used in their numerical form instead of their string form (this is why I would like it if I could use ToString[hours_]
to recognize something like "45"
as the number 45
.).
Is this possible? It seems like my problem is that patterns can be used in the arguments for arbitrary functions so long as they're patterns on expression input. On the other hand, the built-in string pattern tools that can pattern match on strings like StringReplace
expect to take a string in and return a string out.