Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Error on unreachable patterns #191

Open
jonniediegelman opened this issue Jan 31, 2025 · 0 comments
Open

Feature request: Error on unreachable patterns #191

jonniediegelman opened this issue Jan 31, 2025 · 0 comments

Comments

@jonniediegelman
Copy link

jonniediegelman commented Jan 31, 2025

A common mistake I see people who are new to pattern matching make is to see patterns that match on literals and expect to be able to match on variables the same way. For example:

@data Shape begin
    Circle(radius)
    Rectangle(height, width)
end

function whose_circle_is_this(circle)
    my_circle = Circle(1)
    @match circle begin
        my_circle => print("this is my circle")
        Circle(radius) => print("this is someone else's circle")
        _ => print("this isn't a circle at all")
    end
end

The person who wrote this might be surprised to see this result:

julia> whose_circle_is_this(Rectangle(1, 2))
this is my circle

Other implementations of pattern matching prevent this class of error by checking for patterns that make subsequent patterns unreachable. For example, in Python:

class Shape:
    pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

def whose_circle_is_this(circle):
    my_circle = Circle(1)
    match circle:
        case my_circle:
            print("this is my circle")
        case Circle(radius):
            print("this is someone else's circle")
        case _:
            print("this isn't a circle at all")

Trying to define that last function throws the following syntax error:

  File "<python-input-10>", line 4
    case my_circle:
         ^^^^^^^^^
SyntaxError: name capture 'my_circle' makes remaining patterns unreachable

which is pretty helpful to protect against that pretty common error. I suppose it might even be enough to check that a generic catch-all name capture doesn't have any patterns following it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant