Simple guessing game in Clojure not working properly - clojure

I am new to Clojure. As part of practice, I wrote a simple guessing game where the user has to guess a random number chosen by the program between 1-100. I got a basic version working (code snippet 1). Now I want to improve on this by allowing the user to enter an integer from 1 to 100. However the code that I wrote to avoid the user from entering a string is not working (code snippet 2) but the code is not working, no matter what I try.
Code snippet 1 (working)
(ns guessing-game2.core
(:gen-class))
(defn -main []
(let [my-number (inc (rand-int 100))]
(println "I have a number between 1 and 100, guess it: ")
(loop [times 1]
(let [guess (Integer/parseInt (read-line))]
(if (= guess my-number)
(do
(println "You have found it in " times " tries!")
times)
(do
(cond
(< guess my-number) (println "My number is bigger, guess again: ")
(> guess my-number) (println "My number is smaller, guess again: "))
(recur (inc times))))))))
Code snippet 2 (not working)
(ns guessing-game.core
(:gen-class))
(defn -main []
(let [my-number (inc (rand-int 100))]
(println "I have a number between 1 and 100, guess it: ")
(loop [times 1]
(let [guess (Integer/parseInt (read-line))]
(if (and (integer? guess)
(< guess 100))
(if (= guess my-number)
(do
(println "You have found it in " times " tries!")
times)
(do
(cond
(< guess my-number) (println "My number is bigger, guess again: ")
(> guess my-number) (println "My number is smaller, guess again: "))))
(print "Please enter a number")
(recur (inc times))
)
))))

you need to recur outside of the if
(ns guessing-game.core
(:gen-class))
(defn -main []
(let [my-number (inc (rand-int 100))]
(println "I have a number between 1 and 100, guess it: ")
(loop [times 1]
(let [guess (Integer/parseInt (read-line))]
(if (and (integer? guess)
(< guess 100))
(if (= guess my-number)
(do
(println "You have found it in " times " tries!")
times)
(do
(cond
(< guess my-number) (println "My number is bigger, guess again: ")
(> guess my-number) (println "My number is smaller, guess again: "))))
(print "Please enter a number")) ;; <-- moved bracket to here
(recur (inc times))
))))

Related

Compact way in Clojure to print a variable number of command line arguments?

I'm a newbie to Clojure. I think I'm trying to solve this procedurally and there must be a better (more functional) way to do this in Clojure...
The -main function can receive a variable number of 'args'. I would like to print them out but avoid an IndexOutOfBoundsException. I thought I could mimic Java and use a case fall-through to minimize the code involved, but that didn't work:
(defn -main [& args]
(println "There are" (str (count args)) "input arguments.")
(println "Here are args:" (str args))
(let [x (count args)]
(case x
(> x 0) (do
(print "Here is the first arg: ")
(println (nth args 0)))
(> x 1) (do
(print "Here is the 2nd arg: ")
(println (nth args 1)))
(> x 2) (do
(print "Here is the 3rd arg: ")
(println (nth args 2))))))
(doseq [[n arg] (map-indexed vector arguments)]
(println (str "Here is the argument #" (inc n) ": " (pr-str arg))))
map-indexes is like map but adds index number in the beginning.
So it goes item by item through arguments, packs index and item into a vector and by destructruing index number and item are mapped to [n arg].
Since clojure begins counting from 0, you use (inc n) to begin counting from 1. pr-str is pretty print string. The str joins all string components together.
there is also a handy formatting facility in clojure's core library: cl-format, which is the port of common lisp's format syntax. It includes a nice way to print out collections:
(require '[clojure.pprint :refer [cl-format]])
(let [args [:a :b :c :d]]
(cl-format true "~{here is the ~:r arg: ~a~%~}"
(interleave (rest (range)) args)))
;; here is the first arg: :a
;; here is the second arg: :b
;; here is the third arg: :c
;; here is the fourth arg: :d
some more information about what format can do is here

How to end dotimes clojure

I am trying to make a guess the number game in clojure but I keep getting an error saying I can only recur from tail position
(def n (rand-int 100))
(prn n)
(println "You have 10 guesses :D")
(println "HINT: My number is between 1 and 100")
(dotimes [i 10]
(def guess (read-line))
(if (= guess str(n))
(recur (println "Correct!") (println "Incorrect"))))
(I am new to clojure)
dotimes is used to execute the body for sideeffects that exact amount given; there is no means to break - except throwing
loop (or functions) are recur targets. Next you would have to count down the attempts so you can stop, if the user did not guess it:
(loop [attempts 10]
; ...
(recur (dec attempts)))
There are also other problematic things:
Don't def inside other forms. Use let instead.
str(n) will throw, as it will try to call n (ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn)
recuring with println looks fishy, since println returns always nil
How do you end dotimes? You don't. Try using loop instead. There are a lot of issues with your code but that's a start.
though this is discouraged and counterclojurish to even think of short circuiting the execution this way, it is still totally possible with macros (purely for education and fun)
(defmacro return [& x]
`(list '~'return (do ~#x)))
(defmacro dotimes+ [[i n] & body]
`(loop [~i 0 res# nil]
(cond (and (list? res#) (= '~'return (first res#))) (second res#)
(< ~i ~n) (recur (inc ~i) (do ~#body))
:else res#)))
can be used like this:
user> (dotimes+ [i 10]
(println i)
(if (== i 5) (return :short-circuited)))
;; 0
;; 1
;; 2
;; 3
;; 4
;; 5
:short-circuited
user> (dotimes+ [i 10]
(println i)
(if (== i 5) (return)))
;; 0
;; 1
;; 2
;; 3
;; 4
;; 5
nil
user> (dotimes+ [i 10]
(println i))
;; 0
;; 1
;; 2
;; 3
;; 4
;; 5
;; 6
;; 7
;; 8
;; 9
nil
notice, that it still expects the return macro to be called in tail position (similar to recur in loop macro)
(dotimes+ [x 4]
(println "attempt" (inc x))
(let [answer (read-line)]
(println "answer is:" answer)
(if (= answer "yes")
(return "YEAH!!!")
(println "WRONG!"))))

Sleeping barber in Clojure

I'm implementing Sleeping barber using core.async. My current code is:
(def workingtime 10000)
(defn barber [in waiting-room]
(go-loop [served-customers 0]
(let [[v] (alts! [waiting-room in])]
(if (= v :close)
served-customers
(do (Thread/sleep 20)
(recur (inc served-customers)))))))
(defn customers [in waiting-room]
(go-loop [customers-overall 0]
(let [customer-arrival-interval (timeout (+ 10 (rand-int 20)))
[v] (alts! [in customer-arrival-interval])]
(if (= v :close)
customers-overall
(do (>! waiting-room :customer)
(recur (inc customers-overall)))))))
(defn -main [& args]
(let [in (chan)
waiting-room (chan (dropping-buffer 3))
barber-ch (barber in waiting-room)
customers-ch (customers in waiting-room)]
(println "opening the shop for 10 seconds...")
(Thread/sleep workingtime)
(>!! in :close)
(>!! in :close)
(println "closing the shop...")
(println (str "Served " (<!! barber-ch) " customers"))
(println (str "Overall " (<!! customers-ch) " customers came"))))
Is it a correct solution? Can it be improved to make it more Clojure-like?
I wanted to use alt! instead of alts! which makes code easier to read:
(defn barber [in]
(go-loop [served-customers 0]
(alt!
waiting-room (do (Thread/sleep 20)
(recur (inc served-customers)))
in served-customers)))
Runtime throws an exception: Can only recur from tail position. Can I still use alt!?
You could solve the alt!/recur problem by rewriting to:
(defn barber [in]
(go-loop [served-customers 0]
(if (= :waiting-room
(a/alt!
waiting-room ([result] :waiting-room) ;; you could also use result if needed
in ([result] :in))) ;; same here
(do (Thread/sleep 20)
(recur (inc served-customers)))
served-customers)))

conj not adding to end of vector when called via recur

Why does this keep asking Jack if he wants a cup of tea and not the other fathers.
(defn tea-anyone
"Ask 'fathers' if they would like some tea"
[fathers]
(loop [asks 0 to-ask fathers]
(let [[father & others] to-ask]
(println (str "Cup of tea " father "? "))
(if (> asks 6)
(println (str father ": All right then!"))
(recur (inc asks) (conj others father))))))
(tea-anyone ["Jack" "Ted" "Dougle"])
Because others isn't a vector. See for yourself:
(let [[f & o :as a] [1 2 3 4]]
(println f)
(println o)
(println a)
(println (type f))
(println (type o))
(println (type a))
(println (type (conj o 5)))
(println (type (conj a 5))))
To achieve the effect you want, you could use cycle.
Try this:
(recur (inc asks) (conj (vec others) father))

How do I rewrite (def) out of this Clojure code?

I have written a game loop based on deWitter's game loop.
However, I am unsure how to transfer it to a more functional state. I realize that there may need to be some mutable state left within the code but are there any general principles for cleaning up extraneous defs?
(ns beepboop.core)
(def ticks-per-second 25)
(def skip-ticks (/ 1000 ticks-per-second))
(def max-frameskip 5)
(defn update []
(println "Updating."))
(defn display [delta]
(println "Displaying with delta: " delta))
(defn -main []
(def *next-tick* (System/currentTimeMillis))
(while true
(def *loops* 0)
(while (and
(> (System/currentTimeMillis)
*next-tick*)
(< *loops*
max-frameskip))
(update)
(def *next-tick* (+ *next-tick* skip-ticks))
(def *loops* (+ *loops* 1)))
(display
(/ (+ (System/currentTimeMillis) skip-ticks (* -1 *next-tick*))
skip-ticks))))
You should use loop and recur for updating your loop variables:
(defn -main []
(loop [next-tick (System/currentTimeMillis)]
(let [next-next
(loop [next-tick next-tick
loops 0]
(if (and (> (System/currentTimeMillis) next-tick)
(< loops max-frameskip))
(do (update)
(recur (+ next-tick skip-ticks) (+ loops 1)))
next-tick))]
(display (/ (+ (System/currentTimeMillis) skip-ticks (- next-next))
skip-ticks))
(recur next-next))))