Tobias Cohen
Tobias Cohen

Reputation: 20000

Is there a Clojure equivalent of Ruby's #tap method

Ruby provides the #tap method, which allows you to take in a variable and run code on it, but then return the original variable rather than the result of your expression, ie:

def number
  5.tap { |x| print x }   # Prints 5, and returns 5
end

Is there any function built into Clojure that can provide this functionality?

Upvotes: 10

Views: 571

Answers (1)

Alistair
Alistair

Reputation: 8706

You're looking for doto. Here's your example, rewritten using it:

(doto 5
  println)

It works similarly to the -> macro in that it passes the value through a series of functions. A key difference is that it returns the initial value you passed in, rather than what is returned by the final function.

Upvotes: 12

Related Questions