Reputation: 4606
I would like to get the typed value for a field from a record in a Quotation
. It seems like it should be straight forward but I'm a bit lost.
E.g.,
type FullName = { First : string; Last : string }
type Name = { Name : FullName }
let t = { Name = { First = "Jon"; Last = "N" } }
let name = <@ t.Name.First @>
Then I would like to take the value name
and get the Jon
as a string
(not an obj
). How would I do this? Sometimes the return value might be an Array
or another Record
.
Thanks in advance!
Update:
I'll be using this function at the edges of F# so it needs to check for null
:
let getValue (expr: Quotations.Expr<'t>) =
match eval expr with
| null -> None
| x -> Some ((eval expr) :?> 't)
Upvotes: 2
Views: 178
Reputation: 80744
The eval script that you linked will get you half way there - it will compute the actual value of the expression for you. Now all that's left to do is to cast that value to the appropriate type:
let getValue (expr: Quotations.Expr<'t>) = (eval expr) :?> 't
let valueOfName = getValue name // valueOfName : string
Keep in mind that theoretically the cast may crash, but in practice that shouldn't happen, because eval
would always return a value of the right type (unless there is a bug in it).
Upvotes: 4