Created
March 27, 2015 23:29
-
-
Save ctford/42ddfdf0ea9fc3a05ef5 to your computer and use it in GitHub Desktop.
Parsing with Traversy
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 integer [s] (java.lang.Integer/parseInt s)) | |
| (defn parse [from-str] | |
| (lens (fn [x] (-> x from-str list)) | |
| (fn [f x] (-> x from-str f str)))) | |
| (fact "The 'parse' lens focuses on a value in a string." | |
| (-> "2015" (view (parse integer))) => [2015] | |
| (-> "2015" (update (parse integer) inc)) => "2016") | |
| (defn catching [thunk x] (try (thunk) (catch Exception e x))) | |
| (defn safely [l] | |
| (lens (fn [x] (catching #(view x l) [])) | |
| (fn [f x] (catching #(update x l f) x)))) | |
| (fact "The 'safely' lens tolerates exceptions." | |
| (-> "foo" (view (safely (parse integer)))) => [] | |
| (-> "foo" (update (safely (parse integer)) inc)) => "foo" | |
| (-> "2015" (view (safely (parse integer)))) => [2015] | |
| (-> "2015" (update (safely (parse integer)) inc)) => "2016") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment