Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pattern for implementing undo/redo in clojure

Is there an established pattern for implementing undo/redo functionality in clojure or in fp in general?

In an OO language I would go with the command pattern but as it is all about state I wonder if it is idiomatic doing it in clojure.

Are there any libraries that could be of help?

like image 434
nansen Avatar asked Mar 23 '12 22:03

nansen


1 Answers

As with many design patterns you can implement this one as a function in clojure. It depends a little on how you represent state in your program (refs, atoms, agents) through the process is very similar.

You sould simply add a watcher function to your state agent/ref/atom that adds the state to the undo list every time there is an update. then your undo function is just looks it up in the undo list. This has the nice effect of adding your unto to the undo list, allowing for redo as well

My first impression is that refs may be the correct tool for this because you will be able to restore them all in a coordinated fashion, unless of course you can reduce your programs state down to a single identity (in the Clojure sense of the word) then you would not need coordinated update and an agent would work.

like image 143
Arthur Ulfeldt Avatar answered Oct 11 '22 13:10

Arthur Ulfeldt