What can I do to get the following working?
I need to make a function that accepts a Expr list and returns a Expr (Expr list -> Epxr).
type DataObject() =
let data = System.Collections.Generic.Dictionary<int, obj>()
member this.AddValue propertyIndex value = data.Add(propertyIndex, value)
member this.GetValue propertyIndex =
match data.TryGetValue propertyIndex with
| (true, value) -> value
| (false, _) -> box "property not found"
...
(fun args ->
<@@
let data = new DataObject(values)
args |> List.iteri (fun i arg -> data.AddValue i <@@ (%%arg) : string @@>)
data
@@>)
I made the DataObject type to add the values of the args in. But somehow I cannot manage to get the code iterating through the different args (args.[0] .. args.[i]). The message I get is:
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.
If I access the args explicitly (args.[0], args.[1], ...) the solution works, but as soon as I try to add the iteration I run into problems. Because the list of args is flexible in length, this is not a feasible solution for me.
I've tried different approaches, but unsuccesful. Is there some solution?
[Edit]
Adding the feedback of Tomas in my solution brings me this:
type DataObject(values: obj []) =
let propertyMap = new Map<int, obj>(values |> Seq.mapi (fun i value -> (i, value)))
member this.GetValue propertyIndex : obj =
match propertyMap.TryFind propertyIndex with
| Some(value) -> value
| None -> box "property not found"
(fun args ->
let boxedArgs =
args |> List.map (fun arg ->
match arg with
| Quotations.Patterns.Var var ->
if var.Type = typeof<int> then
<@@ (box (%%arg: int)) @@>
else if var.Type = typeof<string> then
<@@ (box (%%arg: string)) @@>
else if var.Type = typeof<System.Guid> then
<@@ (box (%%arg: System.Guid)) @@>
else
failwith ("Aha: " + var.Type.ToString())
| _ -> failwith ("Unknown Expr as parameter"))
<@@ new DataObject(%%(Expr.NewArray(typeof<obj>, boxedArgs))) @@>))
And this works! Only thing is that I want to get rid of the if ... else construction to get the right conversion. Any ideas?
ifwithExpr.Coerce(arg, typeof<obj>)- That should give you an expression that represents the boxing of any other expressionarg. - Tomas Petricek