What is the difference between Pattern Matching and Guards?

前端 未结 4 846
孤城傲影
孤城傲影 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:59

    For one, you can put boolean expressions within a guard.

    For example:

    Just as with list comprehensions, boolean expressions can be freely mixed with among the pattern guards. For example:

    f x | [y] <- x
        , y > 3
        , Just z <- h y
        = ...
    


    Update

    There is a nice quote from Learn You a Haskell about the difference:

    Whereas patterns are a way of making sure a value conforms to some form and deconstructing it, guards are a way of testing whether some property of a value (or several of them) are true or false. That sounds a lot like an if statement and it's very similar. The thing is that guards are a lot more readable when you have several conditions and they play really nicely with patterns.

提交回复
热议问题