开发者

How to check if head is list in F#

开发者 https://www.devze.com 2022-12-13 08:45 出处:网络
Is there a function to check 开发者_高级运维if an object is a list? I did it like this: try let x = unbox<list<obj>>(l)

Is there a function to check 开发者_高级运维if an object is a list?

I did it like this:

try
    let x = unbox<list<obj>>(l)
    ....
with
   | _ -> ...

But i would like to check it with an if or match instead if it is possible.


I'd use:

let isList o =
  let ty = o.GetType()
  if (ty = typeof<obj>) then false
  else 
    let baseT = ty.BaseType
    baseT.IsGenericType && baseT.GetGenericTypeDefinition() = typedefof<_ list>

if (isList o) then
  ...

This will identify lists containing any type of item (int lists, string lists, etc.).


In case you know type of list elements you can use such code:

let is_list (x: obj) =
  match x with
  | :? list<int> -> printfn "int list"
  | :? list<string> -> printfn "string list"
  | _ -> printfn "unknown object"
0

精彩评论

暂无评论...
验证码 换一张
取 消