Browse thread
Request for complete pattern matching
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Martin Jambon <martin_jambon@e...> |
| Subject: | Re: [Caml-list] Request for complete pattern matching |
On Thu, 24 Nov 2005, skaller wrote:
> On Wed, 2005-11-23 at 12:56 -0800, Martin Jambon wrote:
>
>> (* toto.ml *)
>> try
>> while true do
>> match read_line () with
>> / upper / | / _* "." eos / -> print_endline "looks like a sentence"
>> | "." | / ("bye"~ space*)+ / -> print_endline "Bye!"; exit 0
>> | _ -> print_endline "???"
>> done
>> with End_of_file -> ()
>>
>> Notes:
>> - the stuff between slashes are regexps
>> - "." and the last _ are regular OCaml patterns
>> - regexps are replaced by an identifier which is matched after the
>> arrow using library functions, then it is decided whether to jump to the
>> next case or to execute the user-given expression.
>
> Why can't this be done with 'when' clause?
>
> EG:
>
> | ... predicate ... -> ...
>
> replace by
>
> | ... variable .. when predicate(variable)
It was not shown in my example, but the predicate can introduce bindings:
| String (predicate which also defines x) | Int x -> ...
| _ -> ...
You can do this:
# let f = function
`Int n
| `String / (int as n : int) eos / -> 2 * n
| _ -> -1;;
val f : _[> `Int of int | `String of string ] -> int = <fun>
# f (`Int 123);;
- : int = 246
# f (`String "2005");;
- : int = 4010
# f (`String "x");;
- : int = -1
> This would seem to fail only in that 'predicate' code
> cannot refer to another predicate, since the variable
> name is not known.
>
> The 'break' implementation, however, may be overtly
> more efficient (save duplicating predicate evaluations).
>
> --
> John Skaller <skaller at users dot sf dot net>
> Felix, successor to C++: http://felix.sf.net
>
>
--
Martin Jambon, PhD
http://martin.jambon.free.fr
Store and share your bioinformatics tips at http://wikiomics.org