Last active
June 21, 2020 10:36
-
-
Save vasuadari/61c4208401adc757c7d26c2ee9f5c4dc to your computer and use it in GitHub Desktop.
Tap a method in elixir(similar to ruby)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Tap do | |
defmacro tap(tapped_value, do: yield) do | |
quote do | |
var!(t) = unquote(tapped_value) | |
unquote(yield) | |
var!(t) | |
end | |
end | |
defmacro tap(tapped_value, :return, do: yield) do | |
quote do | |
var!(t) = unquote(tapped_value) | |
unquote(yield) | |
end | |
end | |
end | |
defmodule Test do | |
import Tap | |
def run do | |
tap List do | |
IO.puts t.first([1, 2, 3]) | |
IO.puts t.last([1, 2, 4]) | |
end | |
end | |
def run(:return) do | |
tap List, :return do | |
[1, 2, 3] | |
|> t.first() | |
|> t.wrap() | |
end | |
end | |
end | |
IO.puts "=Tap=" | |
IO.inspect Test.run | |
IO.puts "\n=Tap without return=" | |
IO.inspect Test.run :return | |
# Output | |
# =Tap= | |
# 1 | |
# 4 | |
# List | |
# | |
# =Tap without return= | |
# [1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment