0

Python 3.10 adds pattern matching. I was wondering about a few things.

  1. Can you use it as an expression?
  2. If you can, is there a cons operator in Python?
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    No, it's a statement, not an expression. What do you mean by "cons operator"? – Barmar Oct 28 '22 at 17:03
  • Fundamentally, Python *is not a functional programming language*, although it does borrow some tools from functional languages – juanpa.arrivillaga Oct 28 '22 at 17:06
  • 1
    @Barmar so, FP lanaugaes typically have immutable linked lists as a fundamental data structure, the cons operation creates a new list from an element and another list, so `head_element cons another_list` would be similar to Python `[head_element, *another_list]` – juanpa.arrivillaga Oct 28 '22 at 17:09
  • @juanpa.arrivillaga except that in Python, the result doesn't share storage with the original (even if you use a tuple, which is immutable). – rici Oct 28 '22 at 17:11
  • @rici right, of course, Python lists are array lists, not immutable linked lists. Which is why I stated, Python is fundamentally *not* a FP language – juanpa.arrivillaga Oct 28 '22 at 17:12
  • 1
    Python's cons operator can be emulated with spreading: `new_tuple = (x, *old_tuple)` – Barmar Oct 28 '22 at 17:15
  • @juanpa: I know that was obvious to you. But it might not be obvious to OP. Perhaps an actual answer would be more useful than a comment stream. – rici Oct 28 '22 at 17:16
  • 1
    @juanpa.arrivillaga Generators/comprehension are the functional analogs of `for` loops, and the conditional operator is the functional analog of `if/then`. So it's not unreasonable to ask if there's a functional analog of `match`. But there isn't. Interestingly, PHP also recently added a `match` operator, and it *is* an expression. – Barmar Oct 28 '22 at 17:20
  • Cool! Cons exists in form of (head,*tail), but no functional pattern-matching. I was originally going to use it as an alt for ``` e1 if c1 else (e2 if c2 else e3) ``` any better ways? – KianFakheriAghdam Oct 28 '22 at 17:20
  • @KianFakheriAghdam yeah, just use an if-elif-else statement, and dont try to write purefly functional code in Python – juanpa.arrivillaga Oct 28 '22 at 17:22
  • [cons](https://stackoverflow.com/questions/29703516/how-does-cons-work-in-lisp) ([Lisp](https://en.wikipedia.org/wiki/Lisp_%28programming_language%29)) – Peter Mortensen Oct 28 '22 at 22:41
  • It doesn't have the same semantics, but in some ways the list append operator is a type of cons operator. In something like Lisp or ML you build up lists item by item with the cons operator. In Python it is append that you use to build up a list item by item. Since Python isn't a functional programming language, it is more pythonic to use the tools that it already provides than to find a clunky way to emulate something in Lisp. – John Coleman Oct 28 '22 at 23:15

0 Answers0