What is the difference between Pattern Matching and Guards?

前端 未结 4 799
孤城傲影
孤城傲影 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 03:01

    To me it looks like Pattern Matching and Guards are fundamentally the same. Both evaluate a condition, and if true will execute the expression hooked to it. Am I correct in my understanding?

    Not quite. First pattern matching can not evaluate arbitrary conditions. It can only check whether a value was created using a given constructor.

    Second pattern matching can bind variables. So while the pattern [] might be equivalent to the guard null lst (not using length because that'd not be equivalent - more on that later), the pattern x:xs most certainly is not equivalent to the guard not (null lst) because the pattern binds the variables x and xs, which the guard does not.

    A note on using length: Using length to check whether a list is empty is very bad practice, because, to calculate the length it needs to go through the whole list, which will take O(n) time, while just checking whether the list is empty takes O(1) time with null or pattern matching. Further using `length´ just plain does not work on infinite lists.

提交回复
热议问题