State as a Cookie Jar

Aa3555d7ac4b01847ec9f60a930f5ccd?s=47 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!

Aa3555d7ac4b01847ec9f60a930f5ccd?s=128

Joy Heron

October 17, 2017
Tweet

Transcript

  1. State as a Cookie Jar Joy Clark

  2. Joy Clark Consultant @ innoQ joy.clark@innoq.com @iamjoyclark

  3. None
  4. state noun the particular condition that someone or something is

    in at a specific time. @iamjoyclark
  5. mutable adjective liable to change @iamjoyclark

  6. mutable state adjective + noun ?? @iamjoyclark

  7. An entity changes over time… @iamjoyclark

  8. Character #1 @iamjoyclark

  9. Character #2 @iamjoyclark

  10. Character #3 @iamjoyclark

  11. @iamjoyclark Character #4

  12. The value changes over time! @iamjoyclark

  13. 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
  14. 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
  15. 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
  16. swap! explained @iamjoyclark

  17. 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
  18. That’s All For Now! https://github.com/joyclark/cookie-jar @iamjoyclark