Skip to content

Instantly share code, notes, and snippets.

@fumokmm
Created June 2, 2012 23:42
Show Gist options
  • Save fumokmm/2860521 to your computer and use it in GitHub Desktop.
Save fumokmm/2860521 to your computer and use it in GitHub Desktop.
Implementation of 'unless statement' on Groovy & Clojure
(use '[clojure.contrib.test-is :only (is)])
(defmacro unless
([test body]
`(if (not ~test) ~body))
([test body else-body]
`(if (not ~test) ~body ~else-body)))
(is (= 1 (unless false 1)))
(is (nil? (unless true 1)))
(is (= 1 (unless false 1 2)))
(is (= 2 (unless true 1 2)))
(is (= 25
(apply +
(filter #(unless (zero? (rem % 2)) true false) (range 10)))))
(is (= 3510
(apply +
(map #(unless (< % 5) (* 100 %) %) (range 10)))))
class Unless {
static def load() {
Object.metaClass.unless = new Unless().&unless
}
Else unless(boolean test, Closure body) {
if (! test) {
body()
return new Else(doStuff: false)
} else {
return new Else(doStuff: true)
}
}
private class Else {
boolean doStuff
def 'else'(Closure body) {
if (doStuff) body()
}
}
}
// loading unless method
Unless.load()
int sum1 = 0
10.times { i ->
unless (i % 2 == 0) {
sum1 += i
}
}
assert sum1 == 25
int sum2 = 0
10.times { i ->
unless (i < 5) {
sum2 += 100 * i
} 'else' {
sum2 += i
}
}
assert sum2 == 3510
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment