I’m trying to pattern match against a few types that I care about for SQL generation. Ideally I’d like to do this:
let rec getSafeValue record (prop: PropertyInfo) =
match prop.GetValue(record, null) with
| :? string as str -> "'" + str + "'"
| :? Option<_> as opt ->
match opt with
| Some v -> getSafeValue v prop
| None -> "null"
| _ as v -> v.ToString()
The problem is that here, the type parameter to Option<_> gets constrained to match that of record, which ends up being just obj.
I know I can do some pain-in-the-behind reflection-based check (check that it’s a generic type and that it’s an option type based on the name), but I’d rather avoid that if at all possible.
No, there’s no good way to do this using F#’s built-in constructs. However, you could build your own reusable active pattern for this sort of thing:
Now your function might look something like this: