查看模式与模式守卫 [英] View patterns vs. pattern guards

查看:83
本文介绍了查看模式与模式守卫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解GHC中视图模式和模式守卫之间的关系。模式卫兵看起来非常直观,而查看模式看起来有点混乱。它看起来像视图模式更适合处理模式深处的事物,而模式守卫可以更直观地重用视图,但我不太明白。

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 kind of looks like view patterns are better for dealing with things deep in a pattern, while pattern guards can reuse a view more intuitively, but I don't quite get it.

推荐答案

视图模式与模式守卫有重要的重叠。视图模式的主要优点是它们可以嵌套,并避免引入中间模式变量。一个愚蠢的例子:

View patterns have significant overlap with pattern guards. The main advantage of view patterns is that they can be nested, and avoid introducing intermediate pattern variables. For a silly example:

endpoints (sort -> begin : (reverse -> end : _)) = Just (begin, end)
endpoints _ = Nothing

模式守卫需要每个新视图绑定一个新的模式变量,在计算表达式和绑定模式之间交替。

The pattern guard equivalent requires every new view to bind a new pattern variable, alternating between evaluating expressions and binding patterns.

endpoints xs
  | begin : sorted <- sort xs
  , end : _ <- reverse sorted
  = Just (begin, end)
  | otherwise = Nothing

视图模式也可以只使用模式中较早绑定的那些变量,但它看起来确实如此很好:

View patterns can also use only those variables bound earlier in the pattern, but it does look nice:

nonzero :: (a -> Int) -> a -> Maybe a
nonzero f (f -> 0) = Nothing
nonzero _ x = Just x

-- nonzero (fromEnum . not . null) "123" == Just "123"
--                                 ""    == Nothing

模式守卫的主要优势是它们是守卫的简单概括,并且可以包含普通的布尔表达式。我通常更喜欢他们,而不是视图模式,因为我发现 case 的样式,并且看守的重复性比等号风格少。

The main advantage of pattern guards is that they are a simple generalisation of guards, and can include ordinary Boolean expressions. I generally prefer them over view patterns because I find the style of case and guards less repetitious than the equational style.

这篇关于查看模式与模式守卫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆