What is the difference between Pattern Matching and Guards?

前端 未结 4 763
孤城傲影
孤城傲影 2021-01-30 02:14

I am very new to Haskell and to functional programming in general. My question is pretty basic. What is the difference between Pattern Matching and Guards?

Funct

4条回答
  •  感情败类
    2021-01-30 02:45

    In addition to the other good answers, I'll try to be specific about guards: Guards are just syntactic sugar. If you think about it, you will often have the following structure in your programs:

    f y = ...
    f x =
      if p(x) then A else B
    

    That is, if a pattern matches, it is followed right after by a if-then-else discrimination. A guard folds this discrimination into the pattern match directly:

    f y = ...
    f x | p(x) = A
        | otherwise = B
    

    (otherwise is defined to be True in the standard library). It is more convenient than an if-then-else chain and sometimes it also makes the code much simpler variant-wise so it is easier to write than the if-then-else construction.

    In other words, it is sugar on top of another construction in a way which greatly simplifies your code in many cases. You will find that it eliminates a lot of if-then-else chains and make your code more readable.

提交回复
热议问题