Hacker News new | past | comments | ask | show | jobs | submit login

You can easily match over structures, reaching into ASTs to any depth, which makes writing certain optimizations easier. As a very contrived example:

  match expr with
  | Mul (Const x, Const y) -> Const (x*y)
  | Mul (x, Const 2) -> (* optimize as a left shift *)
  | ...



It might not be a great language to create compilers, but python also has a pretty good structured pattern matching as of version 3.10:

  class BinOp:
     def __init__(self, left, right, operator):
         self.left = left
         self.right = right
         self.operator = operator

  sum_of_ints = BinOp(left=1, right=1, operator='+')

  match sum_of_ints:
     case BinOp(left=int(left), right=int(right), operator='+'):
         print(f'Summing int {left} + {right}')
     case BinOp(left=str(left), right=str(right), operator='+'):
         print(f'Concateneting strings {left} + {right}')
     case _:
         print('Don\'t know how to sum this')


One shortcoming (though it's nice that Python has this) of this is that this isn't checked for exhaustiveness by the compiler (because there isn't a Python one) which makes it easy to forget cases and introduce bugs.

Not sure if there are any runtime checks for this?


And look at the difference in verbosity. Lisp is to Python as Python is to Java.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: