[Haskell] Context of a pattern variable
Tomasz Zielonka
tomasz.zielonka at gmail.com
Tue Jan 11 17:12:04 EST 2005
Hello!
I have an idea for a funny extension to pattern matching in Haskell. I wonder
if it was proposed before, and most importantly, if it would be seen as useful.
Currently, pattern variables get only the values of the corresponding subterms
of a matched term. What if we could mark a pattern variable to match not the
corresponding subterm, but *the rest* of the term, as a "context" function.
Such a function would wrap its argument with *the rest*. It would allow to
easily exchange some deep part of a data structure.
The extension introduces a new syntax for patterns, similar to the as-pattern -
@. In the following examples, I'll use @> for this. The syntax
case expr of
(... (ctx @> pat) ...) -> expr2
...
would mean that if the pattern succeeds, then in expr2 ctx is bound to the
function:
(\x -> (... (x) ...))
This is very informal, but I'm sure you understand. Note that the dots stand
for corresponding, but different things in "case" and in the lambda (pattern
vs value).
Here are some simple examples how Haskell code could be rewritten using the
proposed extension:
before:
case t of
(x, y, z) -> (x, y, z+1)
after:
case t of
(_, _, ctx @> z) -> ctx z
before:
case t of
(x, y, (a, Just z)) -> (x, y, (a, z))
after:
case t of
(x, y, (a, ctx @> Just z)) -> ctx z
Note that in the above example ctx is a polymorphic function.
I am not sure this extension would be so useful, that is, if its usefulness
would outweigh the cost of implementation. However, it seems to me that the
implementation would be quite a simple code transformation, that wouldn't
even require to look up datatype definitions. It is probably possible to hack a
working proof of concept eg. in Template Haskell.
BTW, I already see some problems with this syntax. For example, this code
case t of
(x, y, (a, ctx @> Just z)) -> ctx z
wouldn't be equivalent to this one
case t of
(x, y, v) ->
case v of
ctx @> Just z -> ctx z
I would love to hear you opinions. Maybe you can think of some really
convincing (or unconvincing) code examples?
Best regards,
Tomasz
More information about the Haskell
mailing list