Proposal: Procedural pattern matches in function heads

41 views
Skip to first unread message

Isaac Whitfield

unread,
Jan 28, 2018, 12:51:55 PM1/28/18
to elixir-lang-core
Right now if you want to do an "OR" match in a function head, you probably need to use guards and `in` (or duplicate bodies):

def foo(value) when value in [ :this, :that ],
 
do: a_thing
def foo(
value),
 
do: another_thing

# or

d
ef foo(:this),
 
do: a_thing

def foo(:that),
 
do: a_thing
def foo(
value),
 
do: another_thing

It occurs to me that this is quite a lot of typing for something pretty simple, and so I was wondering what people thought about the following:

def foo(:this | :that),
 
do: a_thing
def foo(anything_else),
 
do: another_thing

It could unpack to create an extra foo/1 match. The benefit is less typing, less noise, and it flows better when working (it also matches the syntax of a type spec). Definitions would go from left to right, meaning that the pattern on the left would be declared first so that it's natural when following how things are matching. I took a look around code on GitHub, etc, and it seems the community in general would make good use of this (it'd be even better if we could make it work in a `case` by itself).

Not sure if this has been discussed or shot down before, but figured I might as well be the one to bring it up if it hasn't :)

Thanks all, appreciate thoughts!
IW

Isaac Whitfield

unread,
Jan 28, 2018, 12:54:49 PM1/28/18
to elixir-lang-core
Should have noted that this could work for sub-patterns too, such as:

def foo({ :this | :that, value })

Seems like that would be harder to implement because of the "nesting" context?

Regards,
IW

OvermindDL1

unread,
Jan 29, 2018, 2:15:31 PM1/29/18
to elixir-lang-core
Except what if the `|` operator is overloaded in that context?
Reply all
Reply to author
Forward
0 new messages