Created
August 6, 2016 23:59
-
-
Save joeyates/1caa539b922c829e677e239122333dfa to your computer and use it in GitHub Desktop.
Via a macro, define an Elixir Function with Arity of Provided Arguments
This file contains hidden or 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
| # tags: #code-golf | |
| # Define a method like this: | |
| # `VarArgs.def(:hi, [:there, :world]) | |
| # You get a function: | |
| # `def hi(there, world) ...` | |
| defmodule VarArgs do | |
| defmacro def(name, args) do | |
| params = Enum.map(args, fn(a) -> Macro.var(a, nil) end) | |
| quote do | |
| def unquote(:"#{name}")(unquote_splicing(params)) do | |
| arg_values = Enum.join(unquote(params), ", ") | |
| IO.puts "You called #{unquote(name)}(#{arg_values})" | |
| IO.puts "Params:" | |
| Enum.each((0..length(unquote(params)) - 1), fn(n) -> | |
| IO.puts "#{Enum.at(unquote(args), n)}: #{Enum.at(unquote(params), n)}" | |
| end) | |
| end | |
| end | |
| end | |
| end | |
| defmodule Client do | |
| require VarArgs | |
| VarArgs.def("foo", [:bar, :baz]) | |
| end | |
| Client.foo(42, 13) | |
| # You called foo(42, 13) | |
| # Params: | |
| # bar: 42 | |
| # baz: 13 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment