Search code examples
haskellscoping

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.

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

This code refuses to compile stating that variable bar doesn't exist.

Of course, this is an easy fix but I'm interested in the reasoning behind such scoping rules.


Solution

  • 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.

    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.

    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.

    Maybe there is a way to resolve this circular dependency (I don't know), but it certainly would seem confusing to me.