Week1 Videos

In the first week Martine spoke about the importance of Reactive Programming, I suggest you to watch the videos of the course (Principles of Reactive Programming).

Code for video: Recap: Functions and Pattern Matching

In this video there is an implementation of a Json parser with case classes, and a show methods, one possible implementation in clojure is:
(ns week1.jsonExample)
(def data
{:firstName "John",
:lastName "Smith",
:address {
:streetAddress "21 2nd Stree",
:state "NY",
:postalCode 10021
}
:phoneNumbers [
{:type "home" :number "212 555-1234"}
{:type "fax" :number "646 555-4567"}
]
})
; Utility Functions
(defn pretty_str [s] (str "\"" s "\""))
(defn comma_interposed_str [l] (apply str (interpose ", " l)))
(defn folded_str [[s e] l] (str s (comma_interposed_str l) e))
(def folded_list_str (partial folded_str "[]"))
(def folded_map_str (partial folded_str "{}"))
; Show implementation in clojure as multi methods
(defmulti pretty_json type)
(defmethod pretty_json clojure.lang.PersistentHashMap
[m]
(folded_map_str
(map (fn [[k v]]
(str (pretty_str (name k)) ":" (pretty_json v)))
(seq m)) ))
(defmethod pretty_json clojure.lang.PersistentVector
[s]
(folded_list_str (map pretty_json s)))
(defmethod pretty_json String [e] (pretty_str e))
(defmethod pretty_json nil [n] "null")
(defmethod pretty_json :default [s] (str s))
view raw json.clj hosted with ❤ by GitHub

Here I used a simple Map with Json inside, the show method is pretty_json, instead of match I used multi function.

Code for video: Functional Random Generators

In this video Martin introduce the idea of functional generators to use for tests made with ScalaCheck, we will use clojurecheck that is a property base testing framework like ScalaCheck.
The code of generators is:
(ns week1.generators
(import [java.util Random]))
(defn integers_gen [] (.nextInt (Random.)))
(defn booleans_gen [] (> 0 (integers_gen)))
(defn pairs_gen [] (take 2 (repeatedly integers_gen)))
(defn choose_gen [lo hi] (+ lo (mod (integers_gen) (- hi lo))))
(defn oneOf_gen [& cs] (nth cs (choose_gen 0 (count cs))))
view raw generators.clj hosted with ❤ by GitHub
I jumped the two recap video on language because I think that who came on this blog is a clojure developer, but if you want I can make a little tutorial on clojure.

Comments

  1. Little thing, I wrote function name with _ instead of - Sorry I was quite tired yesterday :)

    ReplyDelete

Post a Comment