clojurebridge-berlin / curriculum

Curriculum for ClojureBridge Berlin workshops
http://clojurebridge-berlin.org/
2 stars 5 forks source link

Un-idiomatic introduction of `update` #34

Open daveliepmann opened 7 years ago

daveliepmann commented 7 years ago

In outline/data_structures.md, the section on updating maps is not idiomatic Clojure:

(def hello {:count 1 :words "hello"})

(update hello :count inc)
;=> {:count 2, :words "hello"}
(update hello :words str ", world")
;=> {:count 1, :words "hello, world"}

This is all technically true, but extremely misleading. A reasonable person would expect hello to then be the "updated" version returned from update, but it's not. Not only is this not explained, but it's weird and unnecessary to def a name then update it anyway. This is a major trap for newcomers to write non-idiomatic Clojure, yet we're explicitly teaching it!

We even say the word "save"!

After the creation [of the map], we want to save a new value associated to the key. The assoc function can be used by assigning a new value to the existing key.

Robsteranium commented 7 years ago

Agreed. What about:

(update {:count 1} :count inc)
;=>     {:count 2}
(update {:words "hello"} :words str ", world")
;=>     {:words "hello, world"}

and:

we want to associate a new value to the key

IIRC update really comes into its own when using quil's functional mode. I found it easier to explain it then when there was an obvious use-case (e.g. update a counter and print to the console, move a circle across the screen).

Indeed I wonder if it's the scope for re-use that makes the need for update (vs assoc) apparent, e.g.

(-> {:count 0}
    (update :count inc)
    (update :count inc)
    (update :count inc)
    (update :count inc)
    (update :count inc))
;=> {:count 5}
daveliepmann commented 7 years ago

IIRC update really comes into its own when using quil's functional mode.

Totally agreed. That's why rather than provide better examples, I think we should remove update so coaches can go over it when the problem arises.

Robsteranium commented 7 years ago

Yeah good idea. It will likely arise in the (potentially confusingly named) update-state function in functional-mode quil. A decent quil example (e.g. frame counter with modulo) should demonstrate update in a practical context - giving them a framework for building animations at the same time. They'll literally be able to see how it works!

daveliepmann commented 7 years ago

I like that approach a lot.