Active patterns and member constraint
Asked Answered
C

2

13

For an inline function one could create a constraint like:

let inline implicit arg =
  ( ^a : (static member op_Implicit : ^b -> ^a) arg)

requiring the given operator or member on the arguments. Is there a way to match based on somthing similar?

I want to create an active pattern where any argument that's passed to the method that matches the constraint of an inlined function as the above triggers that function and everything else ends as part of some error management.

Clad answered 3/9, 2011 at 10:59 Comment(0)
H
30

It looks like you can write inline active patterns too. I haven't used this before, but I tried it now and it seems to work just fine. The Test pattern below can be used with any object that implements Test method that returns option< ^R >:

let inline (|Test|_|) (a:^T) : option< ^R > =
  (^T : (member Test : unit -> option< ^R >) a)

Now you can define some objects that define Test method and match them using the pattern:

type A() =
  member x.Test() = Some(10)

match new A() with
| Test(n) -> printfn "%d" n
| _ -> printfn "failed"

This looks like a very interesting technique, because pattern matching is now a part of the object.

Haematocele answered 3/9, 2011 at 11:53 Comment(0)
M
0

I think you'd have to use reflection, e.g. Have a function that takes o:obj and then reflect over o.GetType()'s members.

Musicale answered 3/9, 2011 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.