Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

clojure

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?

like image 647
Tobias Cohen Avatar asked Aug 06 '15 04:08

Tobias Cohen


1 Answers

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.

like image 101
Alistair Avatar answered Oct 22 '22 12:10

Alistair