PatternMatching
= Pattern Matching =
On 2015-07-10 in #elixir-lang I asked
8:22 AM I get def zzz(conn, params) do
- easy, match when the function is called with two params, I don’t care what they are
8:23 AM and zzz(_conn, %{a: myvar})
matches when the second param is a map that has :a as a key, and binds myvar to the value stored in the map under the key :a
8:24 AM wsmoak, rossjones: That is pattern matching, its equivalent in that case if you do params = %{...}
or %{...} = params
- its more obvious in the second case that it's pattern matching
8:25 AM micmus: thanks! but... def zzz(_conn, params = %{b: myvar}) do
??? I know it matches when the second param is a map with a key of :b (as above). but I'm missing the vocabulary to describe... and also binds params to the value of ... the entire map
8:25 AM how does a value being passed in "hit" both sides of that equals statement?
8:26 AM wsmoak: = is the pattern match assertion, not assignment...if both sides are true, the semantics are preserved
8:26 AM wsmoak: Its easier to look at pattern matching differently. It's looking at that expression and checking if it can be made true - yes it can - by binding params to entire map, and myvar to value of key b
8:27 AM It's like if you did params = %{b: myvar} = the_argument
8:28 AM where the_argument is the passed value
8:28 AM (a = %{foo: "bar"}) = %{foo: "bar", baz: "quux"}
8:31 AM I may have to miss work today. I need time to absorb this. :)
8:37 AM thanks asonge and micmus. very helpful in shifting the way I'm thinking about the syntax.