Search code examples
f#type-providersfsharp.data.typeproviders

Collect TypeProvider ProvidedMethod argument values in list


Here is a simplified snippet of the Provided method which accepts variable number of arguments, in this case 3

ProvidedMethod(methodName = "GetContext", 
               parameters = [ for i in [ 1..3 ] do
                                  yield ProvidedParameter("Param" + string i, typeof<string>) ], 
               IsStaticMethod = true, returnType = typeof<string>, 
               InvokeCode = (fun args -> 
                   <@@ 
                       let dim1 : string = %%args.[0] : string
                       let dim2 : string = %%args.[1] : string
                       let dim3 : string = %%args.[2] : string
                 //    let dims = [for %%arg in args do yield (arg : string) ]// [1] error below
                 //    let dims = [for arg in args do yield (%%arg : string) ]// [2] error below
                       let dims = [ dim1; dim2; dim3 ] //this works
                       String.Join("--", dims)
                   @@>))

I want to collect all arguments in a single list.

What I've tried and did not work is commented in code quotation.

[1]: [FS0010] Unexpected prefix operator in expression
     [FS0594] Identifier expected

[2]: [FS0446] The variable 'arg' is bound in a quotation but is used as part of a spliced expression. This is not permitted since it may escape its scope.

Solution

  • This kind of solution also worked based on the answer suggested in comments: F# Type Provider development: When providing a method, how to access parameters of variable number and type?

    ProvidedMethod(methodName = "GetContext", 
               parameters = [ for i in [ 1..3 ] do
                                  yield ProvidedParameter("Param" + string i, typeof<string>) ], 
               IsStaticMethod = true, returnType = typeof<string>, 
               InvokeCode = (fun args -> 
                   let dims = List.fold ( fun state e -> <@@ (%%string)::%%state @@>) <@@ []:List<string> @@> args
                   <@@ 
                       String.Join("--", dims)
                   @@>))