Kannan Ramamoorthy
Kannan Ramamoorthy

Reputation: 4180

What's the purpose of #_ in Clojure?

I was going through a library code in which they used #_. As gone through multiple references, I understand #_ is discard symbol, which tell the reader to ignore whatever comes next.

Why it is even needed in the first place? If we have something to be ignored, why can't we remove it or just comment it? What's the significance of #_ over commenting?

Upvotes: 7

Views: 1272

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45736

It's super handy when debugging or writing some altered code.

Say you have some massive function, and you want to comment it out for a bit. You have a few options:

You can use line comments:

; (defn some-huge-thing []
;    ... Many lines)

But that's painful unless your IDE has an commenting shortcut, and even then it takes some work. Plus, I've found most IDE's handling of comment-shortcuts to work less than ideally. Sometimes they just add another "layer" of comments instead of removing the existing ones. Line comments also don't help if you only want to comment out a small piece of a function since they aren't context sensitive.

You could use comment:

(comment 
  (defn some-huge-thing []
      ... Many lines))

But I personally don't like comment because here, it requires either nesting the entire thing, or violating Parinfer just to add the comment. Also as @amalloy points out, it ends up expanding to nil, so it can only be used in a context where a stray nil won't effect anything.

... Or, you can use #_:

#_
(defn some-huge-thing []
    ... Many lines)

It doesn't require altering the function at all. It's just two keystrokes to put in, and two to remove. It also doesn't evaluate to nil; it's simply ignored. That means you can use it, for example, to comment out arguments inside of a function call.

I personally use #_ quite often when playing around with different implementations and when I'm trying to isolate a bug. It causes anything comming immediately after it to be ignored, so it's very easy to control what is and isn't executing.

Upvotes: 11

Related Questions