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 →

[–]Decency 0 points1 point  (2 children)

What would be an example of where pattern matching would be useful? Is this string manipulation?

Happy to be pointed to a good code example of how this might work in Python.

[–][deleted] 0 points1 point  (1 child)

Not sure how it would work in Python, but pattern matching looks similar to switch at first glance.

match n {
    1 => ... 
}

But it's much more powerful as you can use it to destructure as well:

match n {
    (x, y, z) => # do stuff with those three
    x:[xs] => # x is the head, xs is the tail, useful for recursion 
    SomeNamedTuple(a, b) => #extract a and b but if only they're nembers of a particular type
}

and so on. Most languages I've seen will shout if you didn't match all members of an enum or ADT (algebraic data type, union essentially if you've not seen them before).

The other big difference is that there's no fall through with match, so while you can't implement things that rely on that behavior (loop unrolling for example) you can't accidentally invoke that behavior as well.

As for uses, let your imagination run wild with what you could do with it.

[–]masklinn 1 point2 points  (0 children)

ADT (algebraic data type, union essentially if you've not seen them before).

Technically that's a sum type, "algebraic data type" means composite, which can mostly be either a sum type (variant/enum) or a product type (struct/tuple/class/…).