If a function takes a keyword as one of its parameters, we normally put it last:
def my_func(a, b, attrs \\ []) do
...
end
So at call site we can write: my_fun(1, 2, option: true)
Similarly, if a function takes another function as one of its parameters, we normally put it last:
def my_fun(a, b, func) do
func.(a, b)
end
So at the call site, we can write nicely as:
my_fun(1, 2, fn a, b ->
a + b
end)
Now, what if my function take both a keyword and a function as parameters?
function last
def my_fun(arg, keyword, func) do
...
end
...
my_fun(1, [
option1: true,
option2: false
], fn arg ->
arg + 1
end)
Or:
keyword last
def my_fun(arg, func, keyword \\ []) do
...
end
...
my_fun(1, fn arg ->
arg + 1
end,
option1: true,
option2: false
)
The problem of function last is that keyword cannot be optional and I have to write []
around it. The problem of keyword last is that function is usually longer than the keyword, so it feels top heavy.
I played around a bit, and it seems like I can do:
high order function
defp private_fun(arg, func, keyword) do
...
end
def my_fun(arg, keyword \\ []) do
&private_fun(arg, &1, keyword)
end
So, at the call site I can do:
my_fun(1,
option1: true,
option2: false
).(fn arg ->
arg + 1
end)
My question is, does it look weird? Because I’ve not seen other people do this.