Created
January 18, 2014 00:29
-
-
Save qerub/8484305 to your computer and use it in GitHub Desktop.
Summing time durations (given as a string) with Clojure and Joda-Time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; lein try joda-time org.clojure/algo.generic | |
;; Let's first shave the parsing yak: | |
(import (org.joda.time.format PeriodFormatterBuilder)) | |
(def h:m-formatter | |
(-> (PeriodFormatterBuilder.) | |
(.appendHours) | |
(.appendSeparator ":") | |
(.appendMinutes) | |
(.toFormatter))) | |
(defn parse-h:m [str] | |
(-> h:m-formatter | |
(.parsePeriod str) | |
(.toStandardDuration))) | |
;; ...and then the addition yak: | |
(require '[clojure.algo.generic.arithmetic :as g]) | |
(import (org.joda.time Duration)) | |
(defmethod g/+ [Duration Duration] [a b] (.plus a b)) | |
;; ...and now the actual task: | |
(require '[clojure.string :refer [split]]) | |
(def input (split "4:30 1:35 3:35 1:18" #"\s+")) | |
(def sum (->> input | |
(map parse-h:m) | |
(reduce g/+))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment