Skip to content

Instantly share code, notes, and snippets.

@jjcomer
Created July 31, 2011 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjcomer/1116199 to your computer and use it in GitHub Desktop.
Save jjcomer/1116199 to your computer and use it in GitHub Desktop.
Clojure State Machine with Application State
(ns StateMachine)
(defn initTodo []
"This function will return a hash representing the inital application state"
{:file "todo.txt"
:some-other-option true})
(defn parse-integer [str]
(try (Integer/parseInt str)
(catch NumberFormatException nfe 0)))
(defn displayMenu
"This function displays the menu and gets the user's input"
[]
(println (str "Todo\n"
"Choose an option\n"
"1) Create a task\n"
"2) Edit a task\n"
"3) Update a task\n"
"4) Delete a task\n"
"5) Quit"))
(case (parse-integer (read-line))
1 :create
2 :edit
3 :update
4 :delete
5 :quit
:error))
(defn programLoop
"This fuction represents the main program loop"
[]
(letfn [
(init []
#(startState (initTodo)))
(startState [state]
#(getUserChoice state))
(getUserChoice [state]
(case (displayMenu)
:create #(createTask state)
:edit #(editTask state)
:update #(updateTask state)
:delete #(deleteTask state)
:quit #(quit state)
#(getUserChoice state)))
(createTask [state]
(println "Create")
#(startState state))
(editTask [state]
(println "Edit")
#(startState state))
(updateTask [state]
(println "Update")
#(startState state))
(deleteTask [state]
(println "Delete")
#(startState state))
(quit [state]
nil)]
(trampoline init)))
(programLoop)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment