Question

Assume the following code:

override x.OnReceive message =
    match message with
    | :? SomeActorMessages as m ->  
        match m with
        | Greet(name) -> Console.WriteLine("Hello {0}",name)
        | Hi -> Console.WriteLine("Hello from F#!")
    | _ -> failwith "unknown message"

Where "message" is of type System.Object is there anything I can do in order to make the pattern matching nicer? e.g. some generic active pattern or some such ?

Maybe this question is too short but I just want to see if there is a way to make the above syntax nicer

Was it helpful?

Solution

You'll need a separate function for the type coercion.

let someActorMessages message =
    match box message with
    | :? SomeActorMessages as m -> m
    | _ -> failwith "unknown message"

override x.OnReceive message =
    match someActorMessages message with ...

That function could also be written as a single case active pattern.

let (|SomeActorMessages|) message =
    ...

override x.OnReceive (SomeActorMessages message) =
    match message with ...

OTHER TIPS

Here is an active pattern solution:

let (|Type|_|) (dummy:'t) (x:obj)=
    match x with
    | :? ('t) as t -> Some(t)
    | _ -> None

unfortunately it requires a dummy variable to make the pattern generic - I can't think of a way around that.

both of these don't work

let (|Type|_|)  (x:obj) : 't option=
let (|Type<'t>|_|)  (x:obj) =
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top