Reputation: 524
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.
Upvotes: 1
Views: 60
Reputation: 524
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)
@@>))
Upvotes: 1
Reputation: 2393
Hacking your solution in the following way actually compiles
InvokeCode = (fun args ->
let dims: string[] = Array.zeroCreate args.Length
let mutable i = 0
let inc () = i <- i + 1
<@@
while i < args.Length do
dims.[i] <- %%args.[i]
inc ()
String.Join("--", dims)
@@>
But I suspect that you rather want to transform a Quotations.Expr[]
of the shape [|Value ("a"); Value ("b"); Value ("c")|]
into a single Quotations.Expr
.
You can use the patterns in Microsoft.FSharp.Quotations.Patterns
to extract stuff from the expressions in the following way
InvokeCode = (fun args ->
let dims =
args
|> Array.choose (function | Value(value, _) -> value |> string |> Some | _ -> None)
|> fun arr -> String.Join("--", arr)
<@@ dims @@>
Upvotes: 2