Last active
April 14, 2024 00:32
-
-
Save drapergeek/d6a0337f65ff0dc331009e328eec756f to your computer and use it in GitHub Desktop.
Elixir Keywords vs Maps in Pattern Matchin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) |
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
Elixir allows partial matching on maps but not on keywords lists.