Hi,
first of all, your original "matchWith" function probably did something slightly different than what you expected - the "pattern" value in the pattern means that it just assigns the value of "y" to symbol "pattern" hiding the original value (tha you've got as parameter). This means that the compiler sees it as:

1
2
3
4
let matchWith pattern1 y = 
match y with 
| pattern2 -> true 
| _ -> false 

Anyway, there is a way for passing patterns as arguments. You can write for example this:

1
2
3
4
5
6
let matchWith (|Pat1|Pat2|) x =
    match x with
    | Pat1 -> true
    | Pat2 -> false

matchWith (|A|B|) 1

... but this still doesn't really help you, because you cannot for example reverse the pattern and call it with (|B|A|) as an argument - the whole name is just an identifier. However, you can achieve this if you use partail patterns instead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let (|A|_|) x =
    match x with
    | 1 | 3 -> Some()
    | _ -> None
let (|B|_|) x =
    match x with
    | 2 | 4 -> Some()
    | _ -> None

let matchWith (|Pat|_|) x =
    match x with
    | Pat -> true
    | _ -> false

matchWith (|A|_|) 1
matchWith (|B|_|) 1
By on 5/31/2009 11:25 AM ()

I don't think there's any way to do it. I would just write all the individual MatchWith functions.

That said, here is some code I was using to fool around with ideas regarding this question, in case you find it interesting...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 

let (|A|B|) x =
    match x with
    | 0 -> A
    | 1 -> B
    | 2 -> B
    | 3 -> A

let ap = (|A|B|)
// hover over 'ap', see type: int -> Choice<unit,unit>

// boilerplate you could stick in a general library somewhere
let Is1Of2 = function | Choice1Of2 _ -> true | _ -> false
let Is2Of2 = function | Choice2Of2 _ -> true | _ -> false

// then knowing that A=1 and B=2 you could write
let MatchA x = ap x |> Is1Of2
let MatchB x = ap x |> Is2Of2
// but in general the individual identifiers 'A' and 'B' do not have meaning except inside a pattern

By on 5/31/2009 10:53 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