Capturing a function with default arguments?

Hey! I have a function defined with default arguments like so:

def my_func(arg1, arg2 \\ %{}, arg3 \\ false)

I want to pass it as a variable, so I’m capturing it as &my_func/3. However, I want to be able to invoke it with only one or two arguments as well, but that gives an error saying “function with arity 3 called with one argument”. Is there a way to do this?

Default arguments are just a syntactic sugar that transforms into functions with different arity:

def my_func(arg1, arg2 \\ %{}, arg3 \\ false)

# arg2 = %{} and arg3 = false
def my_func(arg1)

# arg3 = false
def my_func(arg1, arg2) 

# no default arguments
def my_func(arg1, arg2, arg3)

So if you choose my_func/3, then you are required to pass all arguments when calling it, if you want to avoid passing all the arguments use either my_func/1 or my_func/2.

3 Likes

Or in a bit other words. Default arguments simplify function definition, but they don’t change how functions are called or referenced. &my_func/3 captures the arity 3 version of the created functions as shown by @D4no0.

Got it, thanks. Is there a way to imitate this behaviour then? (without passing the arguments as a list or something like that)

You can look into mfa tuples and apply.

2 Likes