-> "li...">

F # Pattern Matching: Matching Functions / Subtype Lists?

let f (O: obj) = 
    match O with
        | :? (obj -> list<obj>) -> "win"
        | :? list<obj> -> "list!"
        | _ -> "fail"

Console.WriteLine(f(fun x -> ["lol"]))
Console.WriteLine(f(["lol"]))

prints “fail” twice since I believe it is necessary because I give I a function obj -> list<String>that is not obj -> list<obj>. Is there any way to match them? I could drag each list into list<obj>before doing an anonymous function, or I could convert everything to objbefore putting it in the list.

Any of these works makes it coincident, but I thought it was a problem that covariance / contravariance should have solved? Correct me if I am wrong

+5
source share
1 answer

Unfortunately, you cannot solve this problem with the built-in template.

, obj F #, F # Reflection FSharpType.IsFunction . :

open System    
open Microsoft.FSharp.Reflection    

let f (o : obj) =  
  let ty = o.GetType() 
  if FSharpType.IsFunction(ty) then
    let tyFrom, tyTo = FSharpType.GetFunctionElements(ty)
    if tyTo.IsGenericType && tyTo.GetGenericTypeDefinition() = typedefof<list<_>> then
      printfn "win"
    else 
      printfn "wrong function"
  else
    printfn "not a function"

Console.WriteLine(f(fun x -> "lol"))    // wrong function
Console.WriteLine(f(fun x -> ["lol"]))  // win
Console.WriteLine(f(["lol"]))           // not a function

F #, ( ). , , . , , , , .NET Invoke.

. SO. , - () , .. . :

+7

All Articles