Pattern matching

I’ve been playing with pattern matching, mostly to explore how it can work for me. Currently I’m using the ideas package to explore modifying python syntax. In one case, implementing a form of dictionary unpacking, 6 lines of code replaced a 20 – 30 line hideous state machine looping over the whole sequence of tokens on a line of code. See below for the relevant case statement.

{a, b, c} = **dict

case ['{', *between, '}', '=', '**', target, '\n']:
    between = between[::2] # elimate interspersed commas
    pattern = [var(s) for s in between]

Now I want to replace ~= with a call to math.isclose, decoding these examples.

a = b ~= c
if a + b ~= c - d:\n
if (0.1 + 0.1 + 0.1) ~= 0.3:\n

I’m decoding a list of tokens before generating the replacement code and I came up with the following case statement,

case [Token(is_keyword()), *left, Token(string = '~='), *right, Token(string = ':'), Token(string = '\n')]:

However it doesn’t compile, let alone work. The reasons are obvious. The firsts class pattern can’t call a method, only access attributes. Defining a keyword property solves that issue, but I have to edit the package code to do so, after finding where it was installed. But I’m then left with the problem of having two *patterns in the array pattern. I can grab the list in the middle, but my only solution after that was to find the token for ‘~=’ and slice the list to get before and after.

I’ve done some reading around and it looks like a modified version of the Ruby find pattern would solve the problem.

I don’t need a solution to this problem that doesn’t involve pattern matching and am really interested in further discussion.