Live data from Hacker News

JavaScript Pattern Matching Proposal

github.com

131–140 of 254 posts

Re: JavaScript Pattern Matching Proposal

#132

are there any 10+ year old languages that are "advancing" as quickly as JS? Ruby? Python? C++? Why Not?

I love where JS is heading, but perhaps its worth pointing out its a lot easier to rapidly advance a language that historically has been missing huge features.

I'd also argue none are as important as JS. People can choose to not use Ruby, Python or C++, but if you're doing web atm you're pretty much stuck with JavaScript.

Re: JavaScript Pattern Matching Proposal

#133
post #60
post #41

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

There's real value in the fact that ternary operators form expressions , which if statements don't.

Could you elaborate ? I think the only difference is readability, where I favor if-statements over expressions.

Re: JavaScript Pattern Matching Proposal

#134

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.

I think if you look at languages that support them natively, like F#, OCaml/Reason, or Elixir/Erlang, you'll find plenty of examples of real-world uses. Whether those would suffice to illustrate how to apply them in a JS codebase that has this proposal enabled, I cannot say.

However, having gotten used to having them, I can safely say I'll always feel hobbled to work in a language that doesn't have them, so I'm very much in favor of adding them to JS, whether or not this is the proposal that wins out over time.

Re: JavaScript Pattern Matching Proposal

#135
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

Shameless plug but here is my pattern machter [1] :D

Example:

    // simple factorial
    const factorial = n => match(n)
        .when(0, 1)
        .otherwise(n => n * factorial(n - 1));

    // walking a tree
    class Tree {
        constructor(left, right) {
                this.left = left;
                this.right = right;
        }
    }

    class Node {
        constructor(value) {
                this.value = value;
        }
    }

    const T = (l, r) => new Tree(l, r);
    const N = v => new Node(v);

    const walkT = t => match(t)
        .when(Node, v => console.log(v.value))
        .when(Tree, t => { walkT(t.left); walkT(t.right)})
        .otherwise(_ => 'error');

    const mapT = (f, t) => match(t)
        .when(Node, v => N(f(v.value)))
        .when(Tree, t => T(mapT(f, t.left), mapT(f, t.right)))
        .otherwise(_ => { throw new Error('error') });
Works also on deeply nested objects.

[1] https://github.com/MarkusPfundstein/pmatch-js

Re: JavaScript Pattern Matching Proposal

#136
I think it's good to note that this proposal is not far along the process. Pattern matching, if it clears TC39 (a tall order, to be honest), won't land in a spec for half a decade at least I would bet.

So, keep the feedback coming, and don't worry that you'll have to learn this syntax tomorrow. It's still very early, and I wouldn't be surprised if there are at least a couple major revisions before anything like this lands in ECMAScript.

Re: JavaScript Pattern Matching Proposal

#137

I can only see this being a foot gun. Deep equality testing of objects is going to encourage the use of getters. Getters with side effects (no way to prevent them) will basically ruin your day if you try to use pattern matching with them. Additionally, this would be the first "native" way to do deep equality testing of objects. I can see it being abused to do simple one-off checks that could otherwise have been done…

I'm guessing you've not worked with pattern matching of the kind you see in F# or Elixir before? Yes, JS would definitely be better off having this available. Well-developed pattern matching can actually obviate the need for conditionals in a lot of cases, which makes for far cleaner code.

Re: JavaScript Pattern Matching Proposal

#138

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…

I'd argue we should strive to move away from the switch syntax where it's not necessary because it's verbose and has curious semantics [1]. As an example, this should work:

  switch(expr) {
    case 'foo':
      console.log("a string")
      break;
    case { foo: bar }:
      console.log("foo is", bar)
      break;
  }
But how would this work?

  switch(expr) {
    case 'foo':
    case { foo: bar }:
      console.log("foo is", bar)
      break;
  }
Moreover, a big selling point of pattern matching is it is an expression. Keep in mind though case points to a statement list, How do we resolve to a value?

With a "return"?

  function f() {
    switch(expr) {
      case 'foo':
        return 4 // This makes f return 
    }
  }

  function g() {
    var x = switch(expr) {
      case 'foo':
        return 4 // But this doesn't. Is this confusing?
    }
  }
The value of the last statement?

  function g() {
    var x = switch(expr) {
      case 'foo':
        4; // This should resolve to 4
        break; // but is the break necessary now? 
    }
  }
IMO switch sytnax is just legacy left behind by C, and not the best one to keep around, especially given the semantics of pattern matching.

[1]: https://en.wikipedia.org/wiki/Duff%27s_device, not sure if this works on JavaScript (I doubt it), but the point is the switch cases essentially work like "goto"s.

Re: JavaScript Pattern Matching Proposal

#139
I would prefer `match { ... } (value)`, with the `match` keyword essentially creating a function that does the matching when it invoked. Minor seeming change, but then you can think of match as being a generalization of arrow functions instead of a special new language construct (i.e., `(...args) => ...` is just shorthand for `match { ...args => ... }`)

I can understand why though they went with similar syntax to a switch statement though

Re: JavaScript Pattern Matching Proposal

#140

Earlier quoted context omitted.

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

I like it, especially `default` instead of `{}` The leading curly braces in the linked proposal _are_ a bit odd to see, though the repetition of `case` isn't too fun either.

I suspect the example in the proposal refers to an object that doesn't match any of the previous options, but is still an object.

For a default I'd expect there to be another pattern.

Post reply on HN