grain icon indicating copy to clipboard operation
grain copied to clipboard

Feature request: `match {}` syntax for creating matcher function

Open kee-oth opened this issue 2 years ago • 2 comments

Hi!

Currently, if we want to create some lazy matching behavior, we have to do this:

let lazyMatcherFn = matchable => match (matchable) {
  1 => "foo",
  2 => "bar",
  _ => "baz",
}
lazyMatcherFn(1)

There's no real benefit to specifying match (matchable) in scenarios like this. It adds boilerplate and decreases readability (for myself at least).

It would be great to be able to shortcut this by not specifying the matchable. Maybe something like the below:

let lazyMatcherFn = match {
  1 => "foo",
  2 => "bar",
  _ => "baz",
}
lazyMatcherFn(1)

Thanks for taking a look!

kee-oth avatar Jun 01 '22 02:06 kee-oth

OCaml has this syntax as the function keyword and every time I'm reading it in OCaml code, I always think "what the heck is going on here?"

That is to say, I don't like the shortcut at all. With good optimizations, the compiler will erase the lambda for you and the code you write will be clear to consumers.

phated avatar Jun 01 '22 20:06 phated

Conversely, I'm open to this idea (though we'd need to workshop it a bit to make it Grain-like). I do think that we should perhaps wait and see to make sure that this is a common idiom in Grain code before deciding to introduce it as a feature, but I am a fan of OCaml's function keyword.

peblair avatar Jun 01 '22 20:06 peblair