Live data from Hacker News

JavaScript Pattern Matching Proposal

github.com

51–60 of 254 posts

Re: JavaScript Pattern Matching Proposal

#51
post #23

Isn't pattern matching interesting only in a strongly typed environment where the compiler can statically check that you are giving instructions for all possible cases?

While it's obviously safer and super helpful to have a compiler guarantee that there are checks for all cases, having a non-exhaustive pattern match call still be a big improvement over imperative checking of specific fields for control flow.

What I've seen doing fairly fast and loose prototyping and product iteration in Elixir over the last 2 years, is that patten matching can help create better boundaries and data guarantees within a codebase. A bug might still cause a runtime exception, but investigating and fixing the bug can be wayyyyy less painful than in JS, Ruby and friends when a nill/null/undefined/some-other-garbage can be passed very far through the stack before it eventually causes an issue.

Having a pattern match in the code, even a weak, non-typed pattern match on literals or basic data types, can act as an assertion in your code. "This is what the data needs to look like here if anything after is going to work". I think there is a probably an antipattern in taking this too far, coupling all sorts of your codebase to lower-level data structures There are better controls and safety mechanisms that can be implemented, but it can help a lot when there are specific parts of a codebase that are hotspots for issues, or where you're just trying to isolate where a data inconsistency is originating.

Re: JavaScript Pattern Matching Proposal

#52
post #41

Stop using (nested) ternary operator's ! Use if-statements! if(val==1) var res = 1; if(val==2) var res = 2;

You're joking right? first: `var` is completely outdated, second: it should be `else if` for the next conditions, and third: ternary, nested or not, is simply better for that

Re: JavaScript Pattern Matching Proposal

#53
post #43
post #28

Earlier quoted context omitted.

It's more concise than switch, as well as more powerful (can destructure objects). You can't set things equal to the result of a switch. I find the pattern very convenient. let day; switch (date) { case 1: day = "mon"; break; case 2: day = "tues"; break; default: day = "wed"; break; vs let day = match(date) { 1 => 'mon', 2 => 'tues' }

In fairness I think that would look a bit more like this: const getDate = (date) => { switch (date) { case 1: return 'mon' case 2: return 'tues' default: return 'wed' } } let date = getDate(1) Which is, of course, still less terse. What I normally use when I have cases like this is an object-as-a-map. IE: const dates = { 1: 'mon', 2: 'tues' } let day = dates[3] || 'wed';

By the way, I don't think it is a good idea to write a function as a constant. Please compare this

    function getDate(date) { .. } 
to this:

    const getDate = (date) => { ... } 
The first version is more readable. We instantly see that it is a function and in a second case it looks like a constant at first. Also without the equal and arrow sign it looks simpler.

Re: JavaScript Pattern Matching Proposal

#54
post #30
post #23

Isn't pattern matching interesting only in a strongly typed environment where the compiler can statically check that you are giving instructions for all possible cases?

No, not at all. E.g. Erlang is built around pattern matching as a core feature even though it's an untyped language.

Erlang was built from the ground-up with pattern matching in mind, so it works. Instead objects are jammed into the pattern matching system, and where the two disagreed, pattern matching won. (Indeed, Erlang doesn't really even have objects, just some object-like convention.)

In a language that started with an object model that has grown a lot of features, trying to jam pattern matching into it after the fact grows a lot of corner cases fast. For instance, consider:

    a = {x: 1}
    a.toString = function() { return "magic: " + this.x }
Should a pattern match with the string "magic: 1"? Well... probably, because it turns out that "magic: 1" == a is true. But if we do that, how does the pattern match tell a is not in fact a string, if we want to do that? You can answer that question, but the answer will raise further complications of its own. Or you could build a pattern match system around ===, which will raise its own issues. And goodness help the pattern matching syntax if it decides that both are too useful to ignore (a defensible position) and now the syntax needs to support both....

I'd say this proposal is about 10 times too short to be useful, and by the time it's long enough to be useful, it'll be clear that almost nobody will want to learn how to take the already sloppy Javascript equality situation and then learn how to lay down a pattern matching language on top of that.

By contrast, since Erlang was built on pattern matching from day one, = and == have almost no such questions about them. It is very clear what they do. I did have to check what 1 == 1.0 was, even after years of use of Erlang, since I never used floating points in Erlang to speak of. (It is true, which technically I find a bit weird. I'm not sure there's another example of values of different types that can be equal. Note "" == [] because double-quotes are defined as producing lists and strings aren't actually a type, so that's not an exception.)

Re: JavaScript Pattern Matching Proposal

#55

What an ugly syntax. They should follow switch/case syntax for consistency.

I think match cases should be functions, since you have built those anyway. So instead of match (x) { expr... } you would have something like match(x, [ fn... ]) or match(x) { name: fn, name2: fn2 } where fn is like (objectToMatch) => { expr }

It could look like this:

    var x = match (response) {
        case { status:200 }: true;
        case { status: 404 }: false;
        case Number: 0;
        case SomeClass: 1;
        default: -1;
    };

Re: JavaScript Pattern Matching Proposal

#56

Could someone please explain what this could be used for ?

Instead of using if or switch statements to compute a value, you can use a prettier interface. So this: function getStatus(status) { if (status === 200){ return "Success"; } else if (status === 401){ return "Fail!"; } } var myString = getStatus(response.status); Now becomes this: var myString = match (status) { {200} => "Success", {401} => "Fail!" }

More like:

  var myString = match (status) {
    200 => "Success",
    401 => "Fail!"
  }

Re: JavaScript Pattern Matching Proposal

#57
post #24

Javascript is such a mess, this proposal looks really bad, and the guys discussing it are saying things like: "we should make sure that this doesn't look like anything else, so that people who learn the language don't confuse match and switch..." There is also a lot of "we shouldn't break that" messages, and people reply with "oh we already screwed that up here and there, so it's fine"...

It looks pretty much exactly like the Rust match, though.

https://doc.rust-lang.org/stable/book/second-edition/ch06-02...

Re: JavaScript Pattern Matching Proposal

#58

What an ugly syntax. They should follow switch/case syntax for consistency.

Let's see an example of your proposed alternative syntax.

Here you are:

    var x = match (response) {
        case { status:200 }: true;
        case { status: 404 }: new NotFoundError;
        case Number: Math.PI;
        case SomeClass: 1;
        case /^http/: "http error";
        default: -1;
    };

Re: JavaScript Pattern Matching Proposal

#59
post #35

Pattern matching would be a great addition to JS. I built a pattern matching library[1] with a very similar syntax back in 2015 (although I will be the first to admit that it's a naive implementation). It makes validating/traversing deeply-nested objects much less verbose. I'm excited to see where this proposal goes. [1] https://github.com/cshepp/Kasai

Nice library! This actually looks great. The syntax is a bit noisey, but tbh not any more than the actual proposal.
Post reply on HN