Hacker News new | ask | show | jobs
by loup-vaillant 3874 days ago
> You can use, for example, elaborate if-else constructs that firstly try to determine type of the value, then check for values.

That's dynamic typing. Very different from pattern matching over sum types: with dynamic typing, you can basically forget about most compile time guarantees. Seriously, you sound like, "why bother with Ocaml when JavaScript does the same thing?". I can tell you from first hand experience that they do not feel the same at all.

The other classic example, class hierarchies, is also very different from pattern matching —and much more cumbersome. The only language I know of that kinda bridged the two is Scala, with case classes.

1 comments

> That's dynamic typing.

No, that's run-time branch selection. Exactly as with pattern matching (`match .. with ..'), except the latter is more convenient.

> Seriously, you sound like, "why bother with Ocaml when JavaScript does the same thing?".

And you really think I consider elaborate constructions a better thing than concise pattern matching?

> Exactly as with pattern matching

With pattern matching you'll get static checking if your matching is exhaustive. Impossible with an if ladder. Therefore they're not semantically equivalent.

Static checking of a variable, value of which is determined in runtime? How can you do that?
Statically checked pattern matching validates that the provided patterns cover all possible values the variable could have (the whole space of the variables declared/inferred type). So the actual runtime value is not necessary: if the match is exhaustive, there is no possible value that could be taken at runtime that would result in no match.

  type 'a myOption = Some of 'a | None
  let f (Some x) = x*x

Gives this output:

  Warning 8: this pattern-matching is not exhaustive.
  Here is an example of a value that is not matched:
  None
Oh, now I see what you meant. But this has little to do with selecting the branch, what I was talking about the whole time.
Why would you care about selecting the branch in compile time? We're talking about language features semantically equivalent to pattern matching, and, turns out, there are none. As for the importance of the exhaustion check, see the billion-dollar mistake.

Your solution with type and value checks in an if ladder was called "dynamic typing" exactly for this reason - you select paths dynamically in the runtime without any static checks on soundness of this selection.