Skip to content

Instantly share code, notes, and snippets.

@Tebro
Last active October 24, 2017 09:32
Show Gist options
  • Save Tebro/62eaecdea81153b9c519a789b084dd99 to your computer and use it in GitHub Desktop.
Save Tebro/62eaecdea81153b9c519a789b084dd99 to your computer and use it in GitHub Desktop.
Clojure cinemabooker
(ns learningclojure.core
(:gen-class)
(:require [clojure.string :as str]))
(def welcome-message "
Welcome!
These are supported commands:
- show
- book <row> <col>
- quit
")
(defn setup-row [] (into [] (for [_ (range 10)] "_")))
(defn setup-map []
(into [] (for [x (range 10)]
(setup-row))))
(defn seat-string [seat]
(str/join ["[" seat "]"]))
(defn row-string [row]
(str (str/join (map seat-string row)) "\n"))
(defn seat-map-string
"Prints the current data to the screen."
[seat-map]
(str/join (map row-string seat-map)))
(defn book-seat [seat-map row col]
(let
[row-index (dec row)
col-index (dec col)
old-row (seat-map row-index)
new-row (assoc old-row col-index "X")]
(assoc seat-map row-index new-row)))
(defn ask-question [question]
(print (str/join [question ": "]))
(flush)
(read-line))
(defn is-book? [answer]
(= answer "book"))
(defn is-quit? [answer]
(= answer "quit"))
(defn String->Number [str]
(let [n (clojure.edn/read-string str)]
(if (number? n) n nil)))
(defn handle-positive-action [seat-map answer]
(let [args (str/split answer #" ")]
(if (is-book? (args 0))
(book-seat
seat-map
(String->Number (args 1))
(String->Number (args 2)))
(do (print (seat-map-string seat-map))
seat-map))))
(defn -main
[& args]
(print welcome-message)
(loop [seat-map (setup-map)]
(let [answer (ask-question "Enter command")]
(println "")
(if-not (is-quit? answer)
(recur (handle-positive-action seat-map answer))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment