Created
March 26, 2015 07:48
-
-
Save zabirauf/17ced02bdf9829b6956e to your computer and use it in GitHub Desktop.
Railway Oriented Programming macros in Elixir
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 ROP do | |
defmacro try_catch(args, func) do | |
quote do | |
(fn -> | |
try do | |
unquote(args) |> unquote(func) | |
rescue | |
e -> {:error, e} | |
end | |
end).() | |
end | |
end | |
defmacro tee(args, func) do | |
quote do | |
(fn -> | |
unquote(args) |> unquote(func) | |
{:ok, unquote(args)} | |
end).() | |
end | |
end | |
defmacro bind(args, func) do | |
quote do | |
(fn -> | |
result = unquote(args) |> unquote(func) | |
{:ok, result} | |
end).() | |
end | |
end | |
defmacro left >>> right do | |
quote do | |
(fn -> | |
case unquote(left) do | |
{:ok, x} -> x |> unquote(right) | |
{:error, _} = expr -> expr | |
end | |
end).() | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It does not work and I get the following error:
with the following test code:
When I change the macro and rewrite it as below, it works.
Any idea ? Maybe Elixir tries to invoke the function in the process of unquoting in the
bind_quoted
.