Skip to content

Instantly share code, notes, and snippets.

@tcrayford
Created January 22, 2010 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcrayford/283706 to your computer and use it in GitHub Desktop.
Save tcrayford/283706 to your computer and use it in GitHub Desktop.
(ns string_calculator
(:use clojure.contrib.str-utils))
(defn add-numbers [s]
(reduce + (map #(check-num %)
(filter #(not= "" %) (re-split #"," s)))))
(defn check-num [i]
(let [intr (Integer. i)]
(if (> 0 intr)
(throw (IllegalArgumentException. "No negative numbers"))
intr)))
(defn normalize-newlines [s]
(.replaceAll (normalize-custom s) "\n" ","))
(defn normalize-custom [s]
(if (.contains s "//")
(let [[s delim-spec] (re-matches #"//(.*)\n.*" s)
delimiter (java.util.regex.Pattern/quote delim-spec)]
(.replaceAll (nth (re-split #"\n" s) 1)
delimiter
","))
s))
(defn add [s] (if (empty? s)
0
(add-numbers (normalize-newlines s))))
(ns string-calculator-test
(:use clojure.test string_calculator))
(deftest returns_0
(is (= (add "") 0)))
(deftest returns_bare
(is (= (add "1") 1))
(is (= (add "2") 2)))
(deftest adds_numbers
(is (= (add "1,2") 3))
(is (= (add "1,1") 2)))
(deftest newline_as_delimiter
(is (= (add "1\n2") 3))
(is (= (add "1\n1") 2)))
(deftest custom_delimiter
(is (= (add "//+\n1+2") 3))
(is (= (add "//;\n1;3") 4))
(is (= (add "//abc\nabc1abc2") 3))
(is (= (add "//po\npo1po1") 2)))
(deftest no_negatives
;; This test fails
(is (thrown? IllegalArgumentException (add "-1"))) ;; This test fails
(is (= (add "//-\n1-2") 3)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment