← Back to home

Laughter generation in Clojure

My kid comes to me every second day and asks if we can play with some Clojure on the computer. We were bored today, which is awesome in a way, and he asked me to show some stuff I do at work, so I launced a REPL and we began iteratively develop a dumb phrase generator:

user=> (def people ["Mom" "Dad" "Mr. Stinky Feet" "Captain Underpants"])
#'user/people

user=> (def actions ["smelled" "ate" "threw away" "kicked"])
#'user/actions

user=> (def items ["toilet" "cheese" "tomatoes" "poop"])
#'user/items

user=> (defn rand-el [xs] (get xs (int (rand (count xs)))))
#'user/rand-el

user=> (defn laugh! [] (clojure.string/join " " (list (rand-el people) (rand-el actions) (rand-el items))))
#'user/laugh!

user=> (laugh!)
"Mr. Stinky Feet threw away tomatoes"

user=> (laugh!)
"Captain Underpants smelled cheese"

You can see that laugh! is not a pure function, which is fine considering the context, and that it doesn’t have any side-effects. Yet there’s still an exclamantion mark in its name (in Clojure it’s common that exclamation mark is present in functions that deal with mutable state). The exclamation mark is there because this function has generated, independently of its output, so much sincere giggly laughter from my kid that I consider it now very, very side-effectful.

My kid wouldn’t wait for too long if he wouldn’t see the result on the screen. I appreciate having an quick interactive prototyping environment. Obviously it’s not all unique to Clojure, so you can go and play in your own computerized sandbox of choice. And if you wonder, mine’s still better, and green is the best color.

By the way, we did this all using the all-new shiny Replete 2.0 REPL. Can definitely recommend it if you’re in these kind of things. Congrats Mike and Roman on the release!

Last edited on Mar 24, 2019