A little Clojure challenge inspired by Let over Lambda.
Write a macro (you can try a function, but it's impossible) that accepts four arguments:
- an expression that returns a number
- something to return if that number's negative
- something to return if that number's zero
- something to return if that number's positive
Here's the signature: (defmacro nif [expr neg zero pos] ...)
To pass my test, the following form should print "pos!" and return "pos.", with no other side effects:
(nif 10
(do (println "Negative!") "negative.")
(do (Thread/sleep 1000000) "zero.")
(do (println "pos!") "pos."))
May the best lisper win!
Boom! This is great. Couple of style comments, if you're interested:
For nested
if
statements like this, especially as I add more clauses, I like to usecond
. Cond takes pairs of<test-expr>, <result>
and returns the result for the first truthytest-expr
it sees:Beyond that, you might use the
clojure.core/neg?
andclojure.core/pos?
functions vs comparing to zero (totally identical to your solution):Nice job, man. I'll see if I can come up with some tougher ones to toss out there for next time.