Upgrade to Pro — share decks privately, control downloads, hide ads and more …

State as a Cookie Jar

Joy Heron
October 17, 2017

State as a Cookie Jar

What does state have in common with a cookie jar? That's what everybody wants to find out!

Joy Heron

October 17, 2017
Tweet

More Decks by Joy Heron

Other Decks in Technology

Transcript

  1. Clojure (defn take [{cookies ::cookies} to-take] (if (< to-take cookies)

    {::cookies (- cookies to-take)} {::cookies 0})) (defn cookie-monster [cookie-jar to-eat] (take cookie-jar to-eat)) (defn kitten [cookie-jar] (take cookie-jar 1)) (defn grandma [{cookies ::cookies} nr-baked] (if (pos? nr-baked) {::cookies (+ cookies nr-baked)} {::cookies cookies})) Joy Clark https://github.com/joyclark/cookie-jar
  2. Elixir defmodule CookieJar do defstruct cookies: 0 def run(%{cookies: cookies},

    [:cat | actions]) 
 when cookies > 0 do run(%CookieJar{cookies: cookies - 1}, actions) end def run(_, [:monster | actions]) do run(%CookieJar{cookies: 0}, actions) end def run(%{cookies: cookies}, [:grandma | actions]) do run(%CookieJar{cookies: cookies + 1}, actions) end def run(jar, _), do: jar end Mario Mainz https://github.com/mmainz/cookie_jar
  3. Clojure with Mutable State (def cookie-jar (atom {::cookies 5})) (defn

    ghost [cookie-jar] (take cookie-jar 2)) (swap! cookie-jar grandma 5) (swap! cookie-jar kitten) (swap! cookie-jar ghost) @cookie-jar // => 7: retrieves current value of cookie-jar Joy Clark https://github.com/joyclark/cookie-jar @iamjoyclark
  4. In an otherworldly dimension… In the kitchen… (def cookie-jar (atom

    {::cookies 5})) (swap! cookie-jar grandma 5) @cookie-jar => {::cookies 8} (swap! cookie-jar ghost) swap! retrieve {::cookies 5} (grandma {::cookies 5} 5) save! {::cookies 10} swap! retrieve {::cookies 5} (ghost {::cookies 5}) atom changed, retry! retrieve {::cookies 10} (ghost {::cookies 10}) save! {::cookies 8} @iamjoyclark