Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] pattern-matching on partially matched values
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Markus Mottl <markus@o...>
Subject: [Caml-list] pattern-matching on partially matched values
Hello,

I wonder whether this idea has ever been considered for pattern-matching:
Let's say that I have the following (somewhat artificial) code:

  type t = A of a | B of b | C of c

  match foo with
  | A a -> Simply a
  | B b -> This (Is (Very (Complicated (WithB b))))
  | C c -> This (Is (Very (Complicated (WithC c))))

What I'd like to do is factor out the commonality in such a way:

  match foo with
  | A a -> Simply a
  | _ ->
      let f x = This (Is (Very (Complicated x))) in
      match foo with
      | B b -> f (WithB b)
      | C c -> f (WithC c)

When you see "this is very complicated", think of a tree containing
hundreds of (automatically generated) nodes - this is just a small
example.

I could certainly place "let f x = ..." above of the match of "foo",
but this would have several disadvantages: the closure for "f" would
have to be built even when it is not required as in the match case "A a".
Secondly, the definition becomes further removed from the point of use,
making human reasoning more difficult.

It seems to me that it would be rather trivial to maintain a list of
the tried cases for all variables on which a match has been performed,
thus preventing spurious warnings about inexhaustive subsequent matches
on the same. Another example would be:

  match foo with
  | None -> do_something ()
  | _ ->
      let cond = do_something_else () in
      if cond then
        let Some x = foo in
        ...
      else ...

It would then be unnecessary to match all cases immediately to bind
variables. This is not really a problem in this simple example, but may
make a difference when performing superfluous matches on more complicated
patterns.

Would some analysis of this kind make sense in the OCaml-compiler?

Regards,
Markus Mottl

-- 
Markus Mottl                                             markus@oefai.at
Austrian Research Institute
for Artificial Intelligence                  http://www.oefai.at/~markus
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners