Hacker News new | ask | show | jobs
by jzer0cool 1957 days ago
This looks pretty neat. How does this work, do you code and specify a target output? Curious if there is a link somewhere that shows the output files ...

I like learned on the front-page example a multi-state (?) switch statement. What is this called and any other languages support this?

switch [playerA.move, playerB.move] { case [Rock, Scissors] | [Paper, Rock] | [Scissors, Paper]: Winner(playerA);

...

6 comments

It's called pattern matching. You see it a lot in functional languages, not so much in others. Haxe mostly borrowed it from ocaml.

> How does this work, do you code and specify a target output?

Indeed. You can specify multiple targets on multiple builds if your code is compatible with all of them (which happens without too much work when working with libs that do the abstraction for you, like openfl or heaps -- and yeah, that's mostly for games).

It's pattern matching, it's a feature of most functional languages (yes, Haxe is OO, but the language feels veeerrrrry familiar to someone who has used OCaml). Starting to become a more common feature as languages absorb and expose functional-style features (C#, Swift, Kotlin, Rust etc)
That's not pattern matching, it's just switching on arbitrary values. You can do the same thing in d, which doesn't have pattern matching. Pattern matching is something like this:

  switch [playerA.move, playerB.move]
          case [x, x]: Tied()
          case [Rock, x]: Winner(if x == Scissors then playerA else playerB)
It is pattern matching, the semantics are an OCaml/ML family `match` expression.
Ah, so it is[0]. The GP's example doesn't require pattern matching though; as I mentioned, it would work in a language lacking it.

0. https://haxe.org/manual/lf-pattern-matching-structure.html

How so?
[playerA.move, playerB.move] is an array literal value, as are [Rock, Scissors] and the other controlling expressions. The switch simply performs a direct comparison between the two; there need be no destructuring for that to work.
I meant 'how would it work in a language without pattern matching?'

Because it seems to me that it won't. E.g. try this in JavaScript right now with a regular switch statement, it doesn't work. You need actual pattern matching.

I think it's just pattern matching - Rust example:

  let a = "Rock";
  let b = "Paper";
  
  let result = match (a,b) {
      ("Scissors", "Paper") => "A wins",
      ("Paper", "Rock") => "A wins",
      ("Rock", "Scissors") => "A wins",
      ("Paper", "Scissors") => "B wins",
      ("Rock", "Paper") => "B wins",
      ("Scissors", "Rock") => "B wins",
      _ => "Draw"
  };
That's pattern-matching on a tuple, which is common in languages that support destructuring, like Clojure, Scala, OCaml, and other functional programming languages.
This is pattern matching. Support for this exists in Haskell, Scala, and now even Ruby and soon Python.