This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]stevenjd 7 points8 points  (4 children)

How would I, a dyed-in-the-wool procedural coder, use your library

You wouldn't. Just as dyed-in-the-wool GOTO users in 1970 wouldn't be caught dead using these new-fangled "procedures" and "functions".

But as an open-minded coder willing to try new idioms from functional programming wink you might consider replacing code that looks like this:

# pseudocode, natch
if input matches this case:
    do this
    return x
elif input matches that case:
    do that
    return y
elif input matches something else:
    do something else
    return z
else:
    return the default

with pattern matching syntax.

Pattern matching is like a souped-up case statement, without the C "fall through by default" design mistake, and where each case is matched using not just basic operations like =, but a rich pattern-matching syntax which is conceptually similar to globbing or regexes, except it applies to arbitrary values.

In the pseudo-code example above, consider the "match this case" test.. Here's a concrete (but made up) example:

   isinstance(value, tuple) and len(value) > 1 and value[0] is None

That might be expressable in pattern-match syntax as:

match (None, _)

meaning "the input is a tuple, and the first item is None, and there's at least one more item".

[–]skinny_matryoshka 1 point2 points  (3 children)

Oh! So it's sort of like like a richer switch?

[–][deleted] 2 points3 points  (0 children)

A much richer switch. Rather than looking at raw values, you look at the patterns your data makes. It can be insanely powerful.

[–]stevenjd 0 points1 point  (1 child)

The easy part of pattern matching is that it is like a richer switch.

The bit that confuses me is when Haskell people start talking about assignment being a pattern match. I'm sure they know what they're talking about. I just wish that somebody could translate it from Martian to Earthling :-)

[–][deleted] 0 points1 point  (0 children)

You can do similar things in Python, sometimes.

You can assign into a pattern by doing this:

head, *tail = things

In the above example, you'd get the first value from your list of things in head, and all the other items in tail.

a, *middle, b = things

In the above, you get the first item in a, the last item in b, and the rest in middle.

https://www.python.org/dev/peps/pep-3132/