Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to iterate over all arguments passed to a function in Elixir?

Tags:

elixir

I know that one can pass a single list to a function and then iterate over that. However, I prefer to have functions with a more explicit signature. So what I am really looking to know is whether Elixir has anything that is equivalent to the arguments object in Javascript.

As far as I can tell the answer is no. The closest I have seen to a discussion of this topic was in the answer to this question.

The reason I am looking for this feature, is that I have several times found myself applying the same conversion to multiple arguments and it is a bit tedious. Could this be implemented via a macro, perhaps?

like image 930
Daniel C Avatar asked Apr 18 '15 20:04

Daniel C


1 Answers

This is possible, but I would rarely use it:

calling binding() at the top of the function will give you a keyword list of the bindings in scope and their values, which would be the arguments if you called it as the first line of your function, i.e.:

iex(6)> defmodule Mod do
...(6)>   def args(a, b, c) do
...(6)>     for {arg, val} <- binding() do
...(6)>       IO.puts "#{arg} = #{inspect val}"
...(6)>     end
...(6)>   end
...(6)> end


iex(7)> Mod.args(1,2,3)
a = 1
b = 2
c = 3
[:ok, :ok, :ok]
like image 140
Chris McCord Avatar answered Sep 30 '22 19:09

Chris McCord