Skip to content

Instantly share code, notes, and snippets.

@erasmas
Last active August 29, 2015 14:22
Show Gist options
  • Save erasmas/56f4ee290b21ae1314b2 to your computer and use it in GitHub Desktop.
Save erasmas/56f4ee290b21ae1314b2 to your computer and use it in GitHub Desktop.
; In R language there’s a very cool function which allows you to read FWF files w/o a hassle:
; http://stat.ethz.ch/R-manual/R-patched/library/utils/html/read.fwf.html
; Following is a Clojure function to parse a line from a FWF file.
(defn fixed-width-format
[s widths]
(->> (reductions (fn [acc n] (+ acc (Math/abs n))) (cons 0 widths))
(partition 2 1)
(map (fn [[start end]] (subs s start end)))
(keep-indexed (fn [idx e] (if (pos? (nth widths idx)) e)))))
(def line "14460 14484 Boston-Quincy, MA Metropolitan Division")
(fixed-width-format line [5 -3 5 -14 39])
; => ("14460" "14484" "Boston-Quincy, MA Metropolitan Division")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment