5 ms·
In regards to global vs local optimum it is useful to look at the alternatives like pattern matching. For languages that don't support pattern matching or pass
by bcheung 6y ago
In regards to global vs local optimum it is useful to look at the alternatives like pattern matching.
For languages that don't support pattern matching or passing in functions as values, "if" is probably the best you can do with. You might be able to do something with boolean short-circuit operators but it's debatable if that that is better than the if statement.
In React, if you are using JSX, they don't have "if" statements within the markup they just use the boolean short-circuit (&&) operator.
For more ML style languages that support pattern matching, it is often easier to express solutions that way than with traditional if statements. In those situations I would say that "if" is less desirable in terms of expressive power and code readability.
Also, "if / else" only supports 2 cases, with pattern matching you can have an arbitrary amount of cases.
Without pattern matching, expressing more than 2 cases becomes a combination of nested if statements combined with "&&" and "||" expressions. This makes it much harder to read and write.
- wodenokoto 6y ago> Also, "if / else" only supports 2 cases, with pattern matching you can have an arbitrary amount of cases. Coming from a non-pattern marching language (python) I’ve yet to see what the big deal is, maybe you can help. I can have as many elif’s as I need cases and other than maybe not needing to repeat `x==...` I’m not sure what I’m missing out on. With that being said, I do often wish for more elegant solutions to long winded if else
- bcheung 6y agoTo get an intuition for the expressive power you can look up examples of quicksort and factorial in languages that support pattern matching. Haskell is a good example. It is true that you can always just use if statements, it's more about the convenience and cleaner syntax. You can also do destructuring with pattern matching. Pattern matching is almost a requirement if you are going to use algebraic data types. As Paul Graham says in Beating the Averages, you have to look at the other language from the perspective of knowing it. Nobody can really explain it. It's just going to seem equivalent or weird syntax otherwise.
- wodenokoto 6y agoThank you for the thoughtful answer. It made me rethink the premise of my question.