I agree with Robert: pattern matching over

1
System.Type

would be useful. Although I think it should be exposed by admitting typeof expressions to be constants and patten matching like a primitive type.

1
2
3
4
5
let matchType (t:Type) =
    match t with
    | typeof<string> -> printfn "string"
    | typeof<int> -> printfn "int"
    | _ -> printfn "other"

I discovered the need for this feature when trying to make use the active patterns type decomposition example in practice. You can write this great active pattern to decompose the structure of a Type object, but there is no way of matching the atoms of the structure. To work around this you have to use a when-clause to match the atoms via the equality operator -- which undermines the conciseness of using an active pattern in the first place.

1
2
3
4
5
6
7
8
9
10
val (|Named|Array|Ptr|Param|) : System.Type -> ...

let typedef<'a> = 
  let typ = typeof<'a>
  if typ.IsGenericType then typ.GetGenericTypeDefinition() else typ

let listOfWhat x =
  match (box x).GetType() with
  | Named(list, [|t|]) when list = typedef<List<_> > -> Some t
  | _ -> None

It would be much nicer if I could write

1
2
3
4
let listOfWhat x =
  match (box x).GetType() with
  | Named(typedef<List<_> >, [|t|]) -> Some t
  | _ -> None

Both the typeof and typedef functions would need to become pseudo-constants to do this. Additionally typedef doesn't quite work like the C# functionality

1
typeof<List<>>

. Use of the F# typedef function relies on the type inferencer unifying the _ in

1
typedef<List<_> >

with obj by default. However this will fail if

1
System.Object

doesn't satisfy the constraints of the generic type parameter. In which case the programmer is back to the dilemma of inventing a superfluous arbitrary type. So this problem combined with the need for constants to do pattern matching over types might be an argument for why typeof/typedef should be language-primitive operators and not functions.

By on 3/9/2008 3:06 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