It is possible to have multiple rules that evalulate to the same pattern, but each rule must declare the same set of identifiers. Your first rule declares an n identifier while the second rule doesn't. The following code will compile:

1
2
3
4
5
let f x y =
    match x, y with
    | (1, Some(_)) 
    | (2, None) -> ()(* some long expr *)
    | _ -> ()(* expr *)

Alteratively the log expression can always be factored out into a new function. The way you can just call the function from each rule.

Cheers,
Rob

By on 3/27/2008 1:24 AM ()

Hi,
as Robert mentioned, you can't "declare" different variables in two branches of the "match" construct. Unfortunately, you can't express the condition (n > 0) without naming the variable in the expression, but you can use active patterns to deal with this issue:

1
2
3
4
5
6
7
8
9
 
let (|Positive|_|) x =
  if (x > 0) then Some(x) else None

let f x y =
    match x, y with
    | (1, Some(Positive(_))) 
    | (2, None) -> () (* some long expr *)
    | _ -> () (* expr *)

The "(|Positive|_|)" is an active pattern that can be used in the matching construct - it fails when the argument is not negative and otherwise succeeds and returns the number (which is ignored in the match using underscore).

By on 3/27/2008 4:33 AM ()

Hi,
as Robert mentioned, you can't "declare" different variables in two branches of the "match" construct. Unfortunately, you can't express the condition (n > 0) without naming the variable in the expression,

Hi, tomasp

What it the rationale behind this? It seems to be too restrictive. Why not to allow to use common subset of variables bound in each pattern?

Thank you,
nikov

By on 3/27/2008 6:11 AM ()

Allowing the intersection of the identifiers declared seems wasteful, by definition you are declaring some variables that you are not using. Allowing the union of variables to be uses seems dangerous, by definition there will be some variables that are uninitialized. F# tries very hard to avoid the need to deal with null values, uninitialized values would mean the programmer would definitly have to deal with null.

Cheers,
Rob

By on 3/27/2008 6:46 AM ()

Allowing the intersection of the identifiers declared seems wasteful, by definition you are declaring some variables that you are not using.

Hi, Robert.

I cannot agree with this, because these "extra" variables could be used in 'when' conditions.

Thanks,
nikov

By on 3/27/2008 7:36 AM ()

A more flexible syntax for pattern matching with when guards seems to be a frequently requested feature, see for example [link:cs.hubfs.net]

By on 3/27/2008 8:33 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper