PatternMatching

HomePage | RecentChanges | Preferences

Difference (from prior major revision) (no other diffs)

Changed: 1,27c1

Pattern Matching




On 2015-07-10 in #elixir-lang I asked

8:22 AM <wsmoak> 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 <wsmoak> 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 <micmus> 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 <wsmoak> 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 <wsmoak> how does a value being passed in "hit" both sides of that equals statement?

8:26 AM <asonge> wsmoak: = is the pattern match assertion, not assignment...if both sides are true, the semantics are preserved

8:26 AM <micmus> 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 <micmus> It's like if you did params = %{b: myvar} = the_argument

8:28 AM <micmus> where the_argument is the passed value

8:28 AM <asonge> (a = %{foo: "bar"}) = %{foo: "bar", baz: "quux"}

8:31 AM <wsmoak> I may have to miss work today. I need time to absorb this. :)

8:37 AM <wsmoak> thanks asonge and micmus. very helpful in shifting the way I'm thinking about the syntax.



HomePage | RecentChanges | Preferences
This page is read-only | View other revisions
Last edited December 22, 2019 9:51 am by 78-93-98-198.dsl.wavetel.us (diff)
Search: