November 30, 2012 Clojure, Languages 2 comments
November 30, 2012 Clojure, Languages 2 comments
(defn big [st n] (if ( > (count st) n) true false)) ; usage (big "is length of this string longer than 15?" 15)
Day 1: Function that identifies collection.
(defn collection-type [col] (cond (vector? col) (str "vector:") (list? col) (str "list:") (map? col) (str "map:"))) (collection-type [1]) (collection-type (list 1 2)) (collection-type {:chewie :wookie :lea :human})
Day 2: An unless with an else condition using macros.
(defmacro unless [test body] (list 'if (list 'not test) body)) (macroexpand '(unless condition body)) (unless (> 1 10) (println "Did you really think that 1 > 10?"))
Day 2: Type using defrecord that implements a protocol.
(defprotocol Person (writeName ) (writeAge )) (defrecord PersonImpl [name age] Person (writeName [_] (println name)) (writeAge [_] (println age)) Object (toString [this] (str "Name=" (writeName this) "& Age=" (writeAge this) ))) (def andriy (PersonImpl. "Andriy" 25)) (writeName andriy) (writeAge andriy) (println andriy)
Hey! Stop scrolling! :)
Day 3: Sleeping barber problem.
Problem called “sleeping barber.” was created by Edsger Dijkstra in 1965. It has these characteristics:
- A barber shop takes customers.
- Customers arrive at random intervals, from 10 to 30 milliseconds.
- The barber shop has three chairs in the waiting room.
- The barber shop has one barber and one barber chair.
- When the barber’s chair is empty, a customer sits in the chair, wakes up the barber, and gets a haircut.
- If the chairs are occupied, all new customers will turn away.
- Haircuts take 20 milliseconds.
- After a customer receives a haircut, he gets up and leaves.
Write a multithreaded program to determine how many haircuts a barber can give in 10 seconds.
My solution:
(def counter (agent 0)) (def chairs (agent 0)) (def workingTime (agent 1)) (defn haircut [x] (do (Thread/sleep 20) (println "...haircutting...") (+ 1 x))) (defn customer [x] (if (< x 3) (do (send counter haircut) (println "I'm next!") (+ 1 x)) (do (println "I went home. This barber shop sucks!") (- 1 x)))) (defn waitUntilEndOfTheDay [x] (do (Thread/sleep ( * 10 1000) ) (println "[ Clock ticked end of working day ]") (dec x) )) (send workingTime waitUntilEndOfTheDay) (while (pos? @workingTime) (do (Thread/sleep ( + 10 (rand-int 21) )) (send chairs customer))) (println "Barber has finished the day giving " @counter " haircuts.")
…
…haircutting…
I went home. This barber shop sucks!
…haircutting…
I’m next!
…haircutting…
I’m next!
I’m next!
[ Clock ticked end of working day ]
…haircutting…
Barber has finished the day giving 365 haircuts.
nil