简体   繁体   English

ViewPatterns范围界定背后的推理

[英]Reasoning behind scoping of ViewPatterns

Today I came across a weird issue. 今天我遇到了一个奇怪的问题。 A function defined under a where clause wasn't seen by a pattern match. 模式匹配没有看到在where子句下定义的函数。

foo (bar -> 1) = 2
  where
    bar _ = 1

This code refuses to compile stating that variable bar doesn't exist. 此代码拒绝编译声明变量bar不存在。

Of course, this is an easy fix but I'm interested in the reasoning behind such scoping rules. 当然,这是一个简单的解决方案,但我对这种范围规则背后的推理感兴趣。

I'm not an expert in view patterns, nor was I involved in creating them, so I can't tell you "why they were made this way", but I do have an idea about why they work better this way. 我不是视图模式的专家,我也不参与创建它们,所以我不能告诉你“为什么它们是这样做的”,但我确实知道为什么它们以这种方式更好地工作。

The bindings introduced by a where clause are scoped to within a single pattern, not to the function as a whole, and the bindings in the where clause have access to the bindings introduced by the enclosing pattern. where子句引入的绑定限定在单个模式中,而不是作为整体的函数,并且where子句中的绑定可以访问由封闭模式引入的绑定。

For ordinary patterns, this works well, because you can tell whether the pattern is matched just by looking at its constructors, and if so you can bring the pattern's where clause into scope, and if necessary also check pattern guards, etc etc. 对于普通模式,这很有效,因为您可以通过查看其构造函数来判断模式是否匹配,如果是这样,您可以将模式的where子句放入范围,如果需要还可以检查模式保护等。

But for view patterns this is a bit weirder: the functions introduced in the where clause may depend on bindings from the pattern, but in order to even match the view pattern you must have the bindings from the where clause in place as well. 但是对于视图模式,这有点怪异: where子句中引入的函数可能依赖于模式的绑定,但为了甚至匹配视图模式,您还必须具有where子句的绑定。

Maybe there is a way to resolve this circular dependency (I don't know), but it certainly would seem confusing to me. 也许有办法解决这个循环依赖(我不知道),但它肯定会让我感到困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM