Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match with typeof in fsharp

The first match works, but not the second one. Is there any way to match without declaring variables, beside using a chain of if/elif ?

(Note that I use the value elem, while I match the variable t)

  let t = typeof<string>
  match propType with
  | t               ->  elem.GetValueAsString() :> obj
  | typeof<string>  ->  elem.GetValueAsString() :> obj
like image 251
nicolas Avatar asked Mar 09 '12 10:03

nicolas


2 Answers

Your first pattern actually doesn't match typeof<string>. It binds propType to a new value t shadowing the previous t which is equals to typeof<string>.

Since typeof<string> is not a literal, the second pattern doesn't work as well (although it is a redundant pattern in your example). You have to use when guard as follows:

  match propType with
  | t when t = typeof<string> -> elem.GetValueAsString() :> obj
  | t ->  elem.GetValueAsString() :> obj
like image 124
pad Avatar answered Nov 02 '22 09:11

pad


If you're trying to match against the type of a value, you can use the :? operator

Example :

let testMatch (toMatch:obj) = match toMatch with
                        | :? string as s -> s.Split([|';'|]).[0]
                        | :? int as i -> (i+1).ToString()
                        | _ -> String.Empty
like image 45
Cédric Rup Avatar answered Nov 02 '22 08:11

Cédric Rup