Live data from Hacker News

JavaScript Pattern Matching Proposal

github.com

81–90 of 254 posts

Re: JavaScript Pattern Matching Proposal

#81

Leaving aside syntax preferences or other superficial concerns, I find it discouraging that "Motivating Examples" for a proposal include direct references to particular libraries, or particular libraries' examples. I mean, that one (of two) motivations for adding a feature to a language is "Terser, more functional handling of Redux reducers", just feels wrong and casual.

They should be included, as it simply is a valid use-case which most likely will actually be used. However, there should be many more examples or good real-world use-cases. Lack of those concerns me.

Re: JavaScript Pattern Matching Proposal

#82
post #69
post #38

Earlier quoted context omitted.

> It's been "trendy" since the 70's. It's been possible since the '70s but I've seen a lot more talking about it in the last 5-10 years.

Yeah, this applies to all that old Lisp features.

I think of full-featured pattern matching as a fairly recent addition even to Lisp. Lisp has had some pattern-matching constructs forever of course (cond, destructuring-bind, Norvig's sexp matcher from PAIP [1], etc.). But it's only with the more recent emergence of optima [2] as a de-facto standard that it now has really good pattern matching. It was probably the #1 thing I missed in Lisp, after having used ML a bit, until optima came along.

[1] https://github.com/norvig/paip-lisp/blob/master/lisp/patmatc...

[2] https://github.com/m2ym/optima

Re: JavaScript Pattern Matching Proposal

#83

Could someone please explain what this could be used for ?

Pattern matching can be quite powerful, e.g. in C# (which I wish was more indepth / more featured, it still feels a bit immature :( )

```

    switch(foo)
    {
       case TextBox t:
          Console.Writeline(t.Text);
          break;
       case TextBox when t.Text = "Bob":
          Console.WriteLine("Hello Bob");
          break;
       case Combobox c:
          Console.WriteLine($"{c.SelectedItem}");
          break;
       case null:
          Console.WriteLine("Ooops, null!");
          break;
       case int i when i == 5:
          Console.WriteLine("got an int, and it was 5!");
          break;
       case default:
           // handle the default case.
           break;
     }
```

IN languages like F#, pattern matching can compile time check you have covered all bases as well.

e.g, this won't build

````

    type VariableResult =
      | E of string
      | V of string

    let result = V "variable"

    match result with
      | E e -> printf "was error"
```

As i haven't told it how to handle the V case for that discriminated union. So you get nice compile time checking.

Ugh, how do you format code?

Re: JavaScript Pattern Matching Proposal

#84
post #43

Earlier quoted context omitted.

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.

Life is more fun with fat arrows sometimes

    new Promise(function (resolve, reject) {
        methodOne(data, function (error, response) {
            if (erorr) {
                reject(error);
            } else {
                resolve(response);
            }
        })
    })
vs

    new Promise((resolve, reject) => methodOne(data, (error, response) => error ? reject(error) : resolve(response)));

Re: JavaScript Pattern Matching Proposal

#85

Earlier quoted context omitted.

Pattern matching doesn't work the same way as switch/case though. Using that syntax would be misleading and confusing.

I think there's an argument to be made that switch statements already do something adjacent to pattern matching. At the least, it's close enough that something like: switch(expr) { case 'foo': break; case { foo: bar }: break; } Wouldn't strike me as all that strange. It just shifts the semantics from "are you exactly this" to "do you look like this". For non-object primitives (e.g. string or number), I don't think th…

You'll need to insert a newline and 2 spaces before a code block to be recognized as such:

    switch(expr) {
       case 'foo': break;
       case { foo: bar }: break; 
    }
https://news.ycombinator.com/formatdoc

Re: JavaScript Pattern Matching Proposal

#86
post #54

Earlier quoted context omitted.

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…

I believe Erlang inherited its pattern matching from Prolog term unification since Erlang was prototyped as a DSL using Prolog's op built-in predicate (plus other Prolog parsing DSLs such as definite clause grammars). [1]: http://www.swi-prolog.org/pldoc/man?predicate=op%2f3

Heh, OK, Erlang was built for pattern matching from... uhh... the water table up? The mantle up? :)

Re: JavaScript Pattern Matching Proposal

#87
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…

> 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

Exactly. That's one of the key points I make when talking about Erlang: the = sign specifically, and pattern matching more broadly, are like having full-time, production assertions everywhere.

One key to the success of that in Erlang/Elixir, of course, is that you have the infrastructure and language support to manage widespread assertions that can fail.

Re: JavaScript Pattern Matching Proposal

#88

Earlier quoted context omitted.

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; };

so make switch first class?

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

Re: JavaScript Pattern Matching Proposal

#90
Is that really the most pressing problem with Javascript? The lack of one more way of expressing a common pattern? Not, say, the lack of typing or ease of code obfuscation or unintuitive type comparisons the lack of a standard library or ...?
Post reply on HN