Hacker News new | ask | show | jobs
by oskarkv 4413 days ago
For very simple cases there are the threading macros, `->` et al., that you can use like this:

  (-> state 
      (assoc :a val) 
      (update-in [:b :c] f args) 
      (dissoc :d)
      (some-other-fn args))
where :a - :d are keys.

Or you could use monads in much the same way as you would in Haskell; there are libs for that.

Or you could write a new macro (or maybe even function) that does exactly what you want. I did that for a game. It looked like this:

  (call-update-fns game-state hook
    (update-monster-positions)
    (update-monster-ai)
    (let-characters-attack)
    (some-other-stuff))
It would thread the game-state (immutable) through all the functions, and call hook (a function) in between all the functions to send network messages and stuff (to minimize latency), and also collect and return new events that the functions created that I needed to handle (e.g. someone died when the characters attacked). It's almost like the state monad but not quite.
1 comments

And there's synthread[1] for more complex cases:

   (-> {:a 1 :b 2}
     (->/assoc :a inc)
     (->/as {:keys [b]}             
       (->/when (> b 10)
         (->/assoc :large-b true))))
1: https://github.com/LonoCloud/synthread