Created
February 28, 2019 11:47
-
-
Save leonoel/e933ee2b3f1e627063ab1db90d5396f9 to your computer and use it in GitHub Desktop.
Injure implementation of the toy stores & factories example from https://docs.racket-lang.org/guide/units.html
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
{:paths ["."] | |
:deps {injure {:mvn/version "1"}}} |
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 toys | |
(:require [injure.core :refer [target inject]])) | |
(defrecord SimpleToy [color]) | |
(def simple-factory | |
`{:toy-factory/toy? (partial instance? SimpleToy) | |
:toy-factory/toy-color :color | |
:toy-factory/build-toys #(repeatedly % (partial ->SimpleToy :blue)) | |
:toy-factory/repaint #(->SimpleToy %2)}) | |
(defrecord SpecificToy []) | |
(def specific-factory | |
`{:toy-factory/toy? (partial instance? SpecificToy) | |
:toy-factory/toy-color (target :toy-store/store-color) | |
:toy-factory/build-toys #(repeatedly % ->SpecificToy) | |
:toy-factory/repaint #(throw (ex-info "Cannot repaint" {:toy %1 :color %2}))}) | |
(def store | |
`{::color :green | |
::inventory (atom []) | |
::maybe-repaint #(if (= (target ::color) ((target :toy-factory/toy-color) %)) | |
% ((target :toy-factory/repaint) % (target ::color))) | |
:toy-store/store-color (constantly (target ::color)) | |
:toy-store/get-inventory (partial deref (target ::inventory)) | |
:toy-store/stock! #(swap! (target ::inventory) into | |
(map (target ::maybe-repaint)) | |
((target :toy-factory/build-toys) %))}) | |
(def simple-store (merge simple-factory store)) | |
(def specific-store (merge specific-factory store)) | |
(inject simple-store | |
((target :toy-factory/build-toys) 3)) | |
(inject simple-store | |
(let [before ((target :toy-store/get-inventory)) | |
_ ((target :toy-store/stock!) 2) | |
after ((target :toy-store/get-inventory))] | |
[before after])) | |
(inject specific-store | |
((target :toy-store/stock!) 2) | |
(let [inv ((target :toy-store/get-inventory))] | |
[inv (map (target :toy-factory/toy-color) inv)])) | |
(inject (assoc simple-store ::color :purple) | |
((target :toy-store/stock!) 2) | |
((target :toy-store/get-inventory))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment