I am trying to write a function that acts upon a list of maps, where the keys are selected by the user. A minimal example:
# Data
list =
[
%{lower: "a", upper: "A", acute: "á", macron: "ā", grave: "à"},
%{lower: "e", upper: "E", acute: "é", macron: "ē", grave: "è"},
%{lower: "i", upper: "I", acute: "í", macron: "ī", grave: "ì"}
]
Accessing with a static key would look like:
defmodule Matching do
def show_macron(list) do
for %{lower: lower, macron: macron} <- list do
"#{lower}: #{macron}"
end
end
end
Not wishing to duplicate show_upper
show_grave
… I thought I could do this:
defmodule Matching do
def show_general(list, key1 \\ :lower, key2 \\ :macron) do
for %{unquote(key1) => key1, unquote(key2) => key2} <- list do
"#{key1}: #{key2}"
end
end
end
But it returns a ** (CompileError) undefined function key1/0 (there is no such import)
. I suspect this is something to do with scoping, but list
, key1
, key2
is in the same outer scope, so if list
could be accessed, surely the others can too?