Skip to content

Instantly share code, notes, and snippets.

@drapergeek
Last active April 14, 2024 00:32
Show Gist options
  • Save drapergeek/d6a0337f65ff0dc331009e328eec756f to your computer and use it in GitHub Desktop.
Save drapergeek/d6a0337f65ff0dc331009e328eec756f to your computer and use it in GitHub Desktop.
Elixir Keywords vs Maps in Pattern Matchin
defmodule Tester do
def map(%{name: "Jason"} = options) do
IO.puts "HI JASON"
end
def keywords([name: "Jason"] = options) do
IO.puts "EXACTLY JASON"
end
end
Tester.map(%{name: "Jason"}) #=> "HI JASON"
Tester.map(%{name: "Jason", age: 31}) #=> "HI JASON"
Tester.keywords([name: "Jason"]) #=> "EXACTLY JASON"
Tester.keywords([name: "Jason", age: 31]) #=>
#** (FunctionClauseError) no function clause matching in Tester.keywords/1
# wat.ex:7: Tester.keywords([name: "Jason", age: 31])
@drapergeek
Copy link
Author

Elixir allows partial matching on maps but not on keywords lists.

@drapergeek
Copy link
Author

This example assumes that your functions would want to branch on a specific option but also pass the other options along.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment