Skip to content

Instantly share code, notes, and snippets.

@J3RN
Created October 9, 2018 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save J3RN/9957769a4f3288c73398512586724f5f to your computer and use it in GitHub Desktop.
Save J3RN/9957769a4f3288c73398512586724f5f to your computer and use it in GitHub Desktop.
Trying to pattern match in Elixir, variable to variable
pattern = %{foo: "bar", bar: %{baz: "qux"}}
good_data = %{foo: "bar", bar: %{baz: "qux", qux: "asdf"}}
bad_data = %{foo: "baz", bar: %{baz: "asdf"}}
### This is perfect
match?(%{foo: "bar", bar: %{baz: "qux"}}, good_data)
#=> true
match?(%{foo: "bar", bar: %{baz: "qux"}}, bad_data)
#=> false
### Can I replicate it with a variable?
match?(pattern, bad_data)
#=> true
# Matches bad_data?
match?(pattern, good_data)
#=> true
# Pinning
match?(^pattern, good_data)
#=> false
# Doesn't match good_data?
match?(^pattern, bad_data)
#=> false
# Does anything work with the pinned variable?
match?(^pattern, pattern)
#=> true
# Apparently exact matches
# Let's try a case
case good_data do
pattern -> true
_ -> false
end
#=> true
case bad_data do
pattern -> true
_ -> false
end
#=> true
case good_data do
^pattern -> true
_ -> false
end
#=> false
# Same freaking problems as above
# Do raw maps work in function definitions?
defmodule Test do
def match_me(%{foo: "bar", bar: %{baz: "qux"}}) do
true
end
def match_me(_) do
false
end
end
Test.match_me(good_data)
#=> true
Test.match_me(bad_data)
#=> false
# Got that going for us, anyways
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment