Question on pattern matching in a function


i don´t really get it. For example i have 2 functions:

def update_input(conn, %{"id" => id, "key" => key}) do
def update_input(conn, %{"id" => id, "key" => key, "value" => value}) do

Now i call the function through the router with 3 parameters: id, key and value. But instead of the second function the first one runs. If i remove the first one it works, but now when using only 2 parameters there is no match.

Please help me to understand what is going on.


In order to fix this, you need to reverse the function order.

A map with 3 keys will match the pattern where only 2 keys are defined. But a map with 2 keys won’t match on the pattern where 3 keys are defined. I goes from top to button, so first define the function where it matches on the map with 3 keys and then the function for the map with 2 keys.


When you define several pattern-matching functions, always go from the most specific to the most generic one. As @Phillipp said, they are evaluated in the order you put them in the file.

1 Like