Skip to content

Feature request: Error on unreachable patterns #191

@jonniediegelman

Description

@jonniediegelman

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions