saleyn
Need help with a 'required' macro
Is there a way to create a macro called required that could be used like this:
with required(var) <- Map.get(map, key) do
var
else
nil -> raise RuntimeError
end
I tried something like this, but it doesn’t work:
defmacro required(var) do
quote do
unquote(var) when not is_nil(var)
end
end
Most Liked
kip
I don’t think a macro can return just the match part of a with (but happy to be wrong). Nevertheless, this looks more complex that the use case demands. Map.fetch!/2 does basically the same thing:
iex> Map.fetch!(%{a: "a"}, :a)
"a"
iex> Map.fetch!(%{a: "a"}, :b)
** (KeyError) key :b not found in: %{a: "a"}
(stdlib 4.0) :maps.get(:b, %{a: "a"})
so you could simply:
with value <- Map.fetch!(map, key) do
do_something()
end
Even in this case, its not very idiomatic since with's value is to program “happy path” and therefore the with seems redundant in this example and the following would be the simplest:
var = Map.fetch!(%{a: "a"}, :a)
kip
Perhaps I’m missing something, but this is very similar (but not the same) to:
with \
{:ok, p1} <- Map.fetch(map, :param1),
{:ok, p2} <- Map.fetch(map, :param2),
...,
{:ok, pn} <- Map.fetch(map, :paramN)
do
...
end
The difference being that if the key exists and its value is nil then it will still pass unlike your example. Normally when I see use cases like “required” its a data validation case and changesets become a good tool of choice.







