Skip to content

Instantly share code, notes, and snippets.

@milosgajdos
Created October 26, 2015 20:03
Show Gist options
  • Save milosgajdos/13ed25898d35c68a07ec to your computer and use it in GitHub Desktop.
Save milosgajdos/13ed25898d35c68a07ec to your computer and use it in GitHub Desktop.
Find out if all elements in tuple have the same value
iex(5)> foo = {1,2,3}
{1, 2, 3}
iex(6)> bar = {1,1,1}
{1, 1, 1}
iex(7)> {item, item, item} = foo
** (MatchError) no match of right hand side value: {1, 2, 3}
iex(7)> {item, item, item} = bar
{1, 1, 1}
iex(8)>
@rrrene
Copy link

rrrene commented Oct 27, 2015

This is also great to show the difference between normal vars, underscored vars and _ as special case:

    iex(3)>  {_item, _item, _item} = foo
    iex:3: warning: the underscored variable "_item" appears more than once in a match. This means the pattern will only match if all "_item" bind to the same value. If this is the intended behaviour, please remove the leading underscore from the variable name, otherwise give the variables different names
    ** (MatchError) no match of right hand side value: {1, 2, 3}

    iex(3)>  {_, _, _} = foo               
    {1, 2, 3}

    iex(4)>  {item, _, _} = foo
    {1, 2, 3}

Although variables starting with an underscore are not intended to be used, they constitute real variables during pattern matching which must take the same value. In contrast, _ is a "real" wildcard.

This makes, of course, all perfect sense, I just wanted to write it down while re-discovering it 😉

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