Created
May 23, 2017 13:53
-
-
Save pjullah/33231f9183a696ad931c3676f9640054 to your computer and use it in GitHub Desktop.
Clojure Applied
This file contains 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
(ns clojure-applied.core) | |
; define a map - values can be looked up in near constant time. | |
(def earth { | |
:name "Earth" | |
:moons 4 | |
:volume 1.083 | |
:mass 5.972 | |
:type :Planet | |
}) | |
; RESEARCH - Maps, Vectors and sets are implemented | |
; by Hash Array Mapped Tries | |
(get earth :moons) | |
(earth :moons) | |
; using a map to represent an entity type, but it isn't very useful | |
; if we wish to re-use it. | |
(defrecord Planet [ | |
name | |
moons | |
volume | |
mass | |
]) | |
; Two factory functions are automatically | |
; created to assist creating new instances. | |
; the 'positional factory function', which expects | |
; a value for each attribute. | |
; requires all attributes to be included in the | |
; specified order | |
(def earth (->Planet "Earth" 1 1.083 5.972)) | |
(print earth) | |
; and the 'map factory function' that expects | |
; a map with keyed values. | |
; allows omission of optional attributes, provides | |
; more description, and continues to work if | |
; more attributes are added. | |
(def earth | |
(map->Planet {:name "Earth" | |
:moons 1 | |
:volume 1.083 | |
:mass 5.972 | |
})) | |
; Constructing entities with options | |
(declare validate-same-currency) | |
(defrecord Currency [divisor symbol description]) | |
(defrecord Money [amount ^Currency currency] | |
java.lang.Comparable | |
(compareTo [m1 m2] | |
(validate-same-currency m1 m2) | |
(compare (:amount m1) (:amount m2)))) | |
(def currencies {:usd (->Currency 100 "USD" "US Dollars") | |
:eur (->Currency 100 "EUR" "Euro")}) | |
(defn- validate-same-currency | |
[m1 m2] | |
(or (= (:currency m1) (:currency m2)) | |
(throw | |
(ex-info "Currencies do not match." | |
{:m1 m1 :m2 m2})))) | |
(defn =$ | |
([m1] true) | |
([m1 m2] (zero? (.compareTo m1 m2))) | |
([m1 m2 & monies] (every? zero? (map #(.compareTo m1 %) (conj monies m2))))) | |
;;(defn +$ | |
;; ([m1] m1) | |
;; ([m1 m2] | |
;; (validate-same-currency m1 m2) | |
(defn make-money | |
([] (make-money 0)) | |
([amount] (make-money amount :usd)) | |
([amount currency] (->Money amount currency))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment