3 ms·
allow you to implement a single polymorphic function What do you mean by this? And which type of polymorphism?
by Locke1689 12y ago
allow you to implement a single polymorphic function
What do you mean by this? And which type of polymorphism?
- hvidgaard 12y agoPerhaps he is talking about parametric polymorphism? In any case, having the compiler tell you that your pattern matching is not exhastive, and even demand that it is, prevents a whole class of problems and enable you to expand your program and have the compiler help you if you forget to add some new case in a pattern matching.
- kyllo 12y agoParametric. In ML-family languages (SML, OCaml, Haskell) you can define a function that pattern-matches its signature. For example (taken from the Wikipedia article on SML) I could define an algebraic datatype "shape" as such: datatype shape = Circle of loc * real (* center and radius *) | Square of loc * real (* upper-left corner and side length; axis-aligned *) | Triangle of loc * loc * loc (* corners *) Then I could define an "area" function that takes this as a parameter and pattern-matches on its type as such, with a different implementation depending on the type: fun area (Circle (_, r)) = 3.14 * r * r | area (Square (_, s)) = s * s | area (Triangle (a, b, c)) = heron (a, b, c) (* call to Heron's formula function *) Which is also syntactic sugar for: fun area shape = case shape of Circle (_, r) => 3.14 * r * r | Square (_, s) => s * s | Triangle (a, b, c) => heron (a, b, c) If I were to implement the function like: fun area shape = case shape of Circle (_, r) => 3.14 * r * r | Square (_, s) => s * s and forget to include the Triangle case, I would get a compiler error: "match nonexhaustive". Furthermore if I were to include a redundant case or an unreachable case, the compiler would also throw an error informing me of that. Very useful in preventing runtime errors, and languages like Java or C/C++ simply do not provide this.
- Locke1689 12y agoYes, that is how pattern matching works, and no, it has nothing to do with parametric polymorphism. No plans to add extra sugar to immediately switch on the arguments of a function, but I'm pretty sure that switch(arg) is not terrible overhead. I've addressed exhaustivity in a different comment.