Created
August 17, 2011 21:54
-
-
Save nilswloka/1152743 to your computer and use it in GitHub Desktop.
Extreme Startup with Clojure
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 extreme-startup-clj.core | |
(:require compojure.handler) | |
(:use compojure.core) | |
(:use ring.adapter.jetty) | |
(:use clojure.contrib.lazy-seqs)) | |
(declare do-answer) | |
(defn answer [question] | |
(let [q (.substring question 10) | |
answer (do-answer q)] | |
(do (println question ": " answer) | |
{:status 200, | |
:headers {"content-type" "text/plain"}, | |
:body answer}))) | |
(defn extract-numbers [q] | |
(let [number-strings (re-seq #"\d+" q) | |
numbers (map #(Integer/parseInt %) number-strings)] | |
numbers)) | |
(defn plus-answer [q] | |
(str (reduce + (extract-numbers q)))) | |
(defn minus-answer [q] | |
(str (reduce - (extract-numbers q)))) | |
(defn largest-answer [q] | |
(str (apply max (extract-numbers q)))) | |
(defn multiplied-answer [q] | |
(str (reduce * (extract-numbers q)))) | |
(defn primes-answer [q] | |
(let [numbers (extract-numbers q) | |
some-primes (set (take-while #(<= % (apply max numbers)) primes)) | |
result (filter some-primes numbers)] | |
(apply str (interpose ", " result)))) | |
(defn fib-answer [q] | |
(str (nth (fibs) (first (extract-numbers q))))) | |
(defn do-answer [q] | |
(cond | |
(.contains q "plus") (plus-answer q) | |
(.contains q "largest") (largest-answer q) | |
(.contains q "multiplied") (multiplied-answer q) | |
(.contains q "Eiffel") "Paris" | |
(.contains q "James Bond") "Sean Connery" | |
(.contains q "banana") "Yellow" | |
(.contains q "philosopher") "Thales of Miletus" | |
(.contains q "Spain") "Pesetas" | |
(.contains q "Germany") "Angela Merkel" | |
(.contains q "minus") (minus-answer q) | |
(.contains q "primes") (primes-answer q) | |
(.contains q "Fibo") (fib-answer q))) | |
(defroutes the-routes | |
(GET "/" [q] (answer q))) | |
(def application (compojure.handler/api the-routes)) | |
(defonce server (run-jetty #'application {:port 8081, :join? false})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment