evhub / coconut

Simple, elegant, Pythonic functional programming.
http://coconut-lang.org
Apache License 2.0
4.05k stars 120 forks source link

Case/match expression #760

Closed koraa closed 1 year ago

koraa commented 1 year ago

Thanks for the awesome language everybody, I am stoked to be able to use more functional programming idioms in my python code :heart_eyes:

Pardon me if this has been discussed before, but how about a case expression?

def classify_special_number(a) =
  case a then:
    match 7: "lucky"
    match 42: "the answer"
  else: "just some number"

I know I could use addpattern functions, but I kind of think this is neater as it does not require me to repeat the function name and having a case expression would come in handy in many places.

Basically in a case expression every block should behave like an assignment function.

This mechanism could be extended to allow for the "everything is an expression" idiom in many places:

evhub commented 1 year ago

Glad you're enjoying Coconut!

Closing as a duplicate of #190 to keep discussion in one place. My current thoughts on this: assignment function definition is nice for short, simple functions like def f(x) = x * 2, but imo return is more clear for longer, more complex functions like the one above. So I'd recommend either using addpattern like you mentioned, or just writing:

def classify_special_number(a):
  match a:
    case 7: return "lucky"
    case 42: return "the answer"
  else: return "just some number"
koraa commented 1 year ago

OK thanks, I didn't use the right keywords to search then :D