Created
June 7, 2013 07:02
-
-
Save anonymous/5727514 to your computer and use it in GitHub Desktop.
A quick example of some text handling techniques for Clojure
This file contains hidden or 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
(defn to-float [x] | |
(when x (Float/parseFloat x))) | |
(defn to-int [x] | |
(when x (Integer/parseInt x))) | |
(defn process-data [data] | |
(let [field-format (array-map :id to-int | |
:name identity | |
:score to-float)] | |
(->> data | |
(map (fn [fields] ;; Create record | |
(->> fields | |
(map #(get {"-" nil "" nil} % %)) ;; Normalize field values, handle nil | |
(map #(%1 %2) (vals field-format)) ;; Convert fields into proper types | |
(zipmap (keys field-format)) ;; Convert record into map | |
)))))) | |
(comment | |
(process-data [["1" "one" "0.1"] | |
["2" "two" "0.2"] | |
["3" "three" "0.3"] | |
["4" "four" "-"]]) | |
;; returns | |
({:score 0.1, :name "one", :id 1} | |
{:score 0.2, :name "two", :id 2} | |
{:score 0.3, :name "three", :id 3} | |
{:score nil, :name "four", :id 4}) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment