Skip to content

Instantly share code, notes, and snippets.

@ctford
Created March 27, 2015 23:29
Show Gist options
  • Select an option

  • Save ctford/42ddfdf0ea9fc3a05ef5 to your computer and use it in GitHub Desktop.

Select an option

Save ctford/42ddfdf0ea9fc3a05ef5 to your computer and use it in GitHub Desktop.
Parsing with Traversy
(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