View patterns vs. pattern guards

后端 未结 2 985
梦如初夏
梦如初夏 2021-02-05 19:18

I\'m trying to get a sense of the relationship between view patterns and pattern guards in GHC. Pattern guards seem quite intuitive, while view patterns seem a bit confusing. It

2条回答
  •  名媛妹妹
    2021-02-05 19:59

    View patterns let you project a value before pattern matching on it. It can almost be thought of as a short cut for

     foo x = case f x of
       ...
    

    There's a bit of sugar on top for dealing with more complex views, but basically that's it. On the other hand, pattern guards are strictly more general,

    1. They can include arbitrary boolean conditions for matching
    2. They can match using more than one of the variables

    I favor view patterns when I'm doing something "lens-like". I have a big piece of data and I'm interested in one particular view of it. For example, with lens

    foo (view someLens -> Bar baz quux) = ...
    

    Pattern guards tend to work well when you want something closer to a more flexible case expression.

提交回复
热议问题