3

Documentation says:

(do exprs*)
Evaluates the expressions in order and returns the value of the last. If no expressions are supplied, returns nil.

However, I just did this:

(defn blah []
  (print "how")
  (print "now")
  (print "brown")
  (print "cow")
  (+ 1 1))

Resulting in this:

hownowbrowncow2

So why is this thing needed again?

Mark Karpov
  • 7,499
  • 2
  • 27
  • 62
user1992634
  • 764
  • 7
  • 16

2 Answers2

4

Generally, do is a special form that allows one to execute several forms in order, presumably for side-effects, because do form returns result of evaluation of its last form, so that there is no reason to use it with pure functions. Simply put, you can think of do as of some kind of wrapper for non-pure code. There are analogues of this form in every Lisp, for example in Common Lisp it is called progn.

do is implicitly used in such macros as: defn, when, when-not, and others.

From practical point of view, you can use it with if statements (see Tomo's answer) and it comes in handy when you write macros that have 'body' arguments (like body of a function in defn).

Community
  • 1
  • 1
Mark Karpov
  • 7,499
  • 2
  • 27
  • 62
  • Any idea why `do` is implemented as special form and not as a macro? As I can see, it is pretty easy to implement such a macro... – neoascetic Aug 03 '16 at 22:36
2

You would use it in forms like if, which only takes a single s-exp as "then" or "else".

(if (= a b)
    (do (println "Yes") (something))
    (do (println "No") (something-else)))
Tomo
  • 3,431
  • 5
  • 25
  • 28