Skip to content

Instantly share code, notes, and snippets.

@abetkin
Created April 17, 2020 08:54
Show Gist options
  • Save abetkin/539140873ad46a6e3de645e7797d8850 to your computer and use it in GitHub Desktop.
Save abetkin/539140873ad46a6e3de645e7797d8850 to your computer and use it in GitHub Desktop.
defmodule Wrapper do
defmacro apply(call, [do: block]) do
{wrapper, _opts, args} = call
func = makefun(do: block)
{wrapper, [], [:wraps, func] ++ args}
end
def makefun(do: block), do:
{:fn, [], [{:->, [], [[], block]}]}
end
defmodule Ex do
require Wrapper
# a wrapper that increments each of 2 values returned
def incr(:wraps, f, x, y) do
{a, b} = f.()
{a+1, b+1}
end
def f(x, y) do
incr(x, y) |> Wrapper.apply do
{x, y}
end
end
# a convenience macros for incr wrapper
defmacro incr(x,y, do: block) do
{wrapper, _opts, _args} = quote do Ex.incr end
func = Wrapper.makefun(do: block)
{wrapper, [], [:wraps, func, x, y]}
end
def g(x, y) do
incr(x, y) do
{x, y}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment