Created
July 31, 2011 00:43
-
-
Save jjcomer/1116199 to your computer and use it in GitHub Desktop.
Clojure State Machine with Application State
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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