这是Provided方法的简化代码段,它接受可变数量的参数,在这种情况下为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)
@@>))
我想将所有参数收集在一个列表中。
我在代码中引用了我尝试过但没有起作用的内容。
[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.
答案 0 :(得分:2)
以以下方式破解您的解决方案实际上可以编译
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)
@@>
但是我怀疑您想将Quotations.Expr[]
形状的[|Value ("a"); Value ("b"); Value ("c")|]
转换为单个Quotations.Expr
。
您可以通过以下方式使用Microsoft.FSharp.Quotations.Patterns
中的模式从表达式中提取内容
InvokeCode = (fun args ->
let dims =
args
|> Array.choose (function | Value(value, _) -> value |> string |> Some | _ -> None)
|> fun arr -> String.Join("--", arr)
<@@ dims @@>
答案 1 :(得分:1)
这种解决方案也可以基于评论中建议的答案: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)
@@>))