I have a situation where I am handed an object and need to produce a string. In most cases, I can just call .ToString() and be done with it (works for strings, numbers, dates, etc.)
One situation where this doesn't work is a byte array representing a GUID. In that case, ToString() simply reports "System.Byte[]". I am trying to use pattern matching to catch byte arrays so that I can customize the string-ification. But I can't figure out how to match a byte array (or, really, any array) except via the Array pattern. A GUID is 16 bytes long, and I really don't want to have a pattern with 16 named array elements. Also, using the array pattern causes F# to want an array as the input, rather than an object:
match value (* <-- obj *) with
| [|
b1; b2; b3; b4;
b5; b6; b7; b8;
b9; b10; b11; b12;
b13; b14; b15; b16
|] -> (* do some magic here later... *) b1.ToString()
| x -> x.ToString()
> This expression was expected to have type obj but here has type 'a []
I tried to use Type test pattern, but it results in a compiler error (seems to have a problem with the opening square bracket):
match value (* <-- obj *) with
| :? byte[] as guid -> (* do some magic here later... *) guid.ToString()
| x -> x.ToString()
> Unexpected symbol '[' in pattern matching. Expected '->' or other token.
The F# documentation on Pattern Matching doesn't seem to cover array type tests, and I haven't found anything via Google that suits my needs. What's the syntax here?
You can use:
match o with
| :? array<byte> as guid -> ...
You can also put brackets around the type name:
match o with
| :? (byte[]) as guid -> ...
or
match o with
| :? (byte array) as guid -> ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With