What are advantages of pattern matching over conditionals in FP (in layman's terms)?

Viewed 329

In layman's terms, what exactly are the benefits of pattern matching, other than historical reasons? The answers I came across are mostly beyond my level (e.g I don't understand what heap allocation has to do with this).

I have a background in Python, only recently picking up Haskell again.

So I had a hard time understanding other answers given in the context of other languages.

1 Answers

One of the most useful aspects of using pattern matching instead of conditionals is to allow APIs involving only total operations, i.e. operations which never cause runtime exceptions / errors.

Consider this code, exploiting an hypothetical function runOperationOn, returning Maybe String.

case runOperationOn someData of
   Just res -> putStrLn ("The operation was successful: " ++ res)
   Nothing  -> putStrLn "The operation failed!"

Here, pattern matching allows to check whether the operation succeeded and get the result on success, at the same time. The last part is crucial. Using booleans, we would need to use something like:

if canRunOperationOn someData
then putStrLn ("The operation was successful: " ++ doRunOperationOn someData)
else putStrLn "The operation failed!"

This looks similar, but it has significant drawbacks compared to pattern matching:

  • It splits the functionality into two functions: one to check if we can perform the operation, and one to actually do it.
  • It involves a partial function doRunOperationOn which returns a String, but will crash on invalid inputs.

The latter is quite bad, since it puts some burden on the programmer, who has to remember to ask "can I?", or risk a crash.

Related