When to favor untyped over typed quotations in F#?

送分小仙女□ 提交于 2019-12-21 09:02:12

问题


F# has both typed and untyped code quotations and I wonder what are the use cases where one would choose one over the other?

Is the distinction just convenience and untyped and typed quotations are convertible to each in all cases or are typed quotations e. g. a subset of the ones possible with untyped quotations?

Are there any examples which only work with typed, but not with untyped quotations – or the other way around?


回答1:


In general, I'd recommend using typed quotations whenever you can. As usual, the types will allow you to statically enforce some correctness conditions that might otherwise cause failures at runtime. Consider:

let one = <@@ "one" @@>
// exception at runtime
let two = <@@ 1 + %%one @@>

as opposed to

let one = <@ "one" @>
// compile time error: the type 'string' does not match the type 'int'
let two = <@ 1 + %one @>

Additionally, sometimes untyped quotations need additional type annotations in cases where typed quotations don't:

// ok
let l = <@ [1] @>
let l2 = <@ List.map id %l @>

// fails at runtime (obj list assumed instead of int list)
let l = <@@ [1] @@>
let l2 = <@@ List.map id %%l @@>

// ok
let l = <@@ [1] @@>
let l2 = <@@ List.map (id:int->int) %%l @@>

However, if you're building something extremely generic out of quotations, it may not be possible to use typed quotations (e.g. because the types aren't statically known). In that sense, untyped quotations give you more flexibility.

Also note that it's extremely easy to convert between typed and untyped quotations as needed (upcast an Expr<_> to Expr to go from typed to untyped; use Expr.Cast to go the other way).




回答2:


Typically, consumers of quotation processing libraries will use typed quotations. Whereas quotation processing authors need to work with untyped quotations.

That is, you won't often directly create untyped quotations using the (<@@ @@>) operator. But, in order to recursively process a quotation using various F# core library active patterns, such as the Quotations.Patterns module, you work with quotations in their untyped form.

Note that Expr<'T> extends Expr and doesn't really add much information to it. That is, typed quotations are really just an illusion, all the captured metadata is in the Expr object and only available at runtime.



来源:https://stackoverflow.com/questions/10640978/when-to-favor-untyped-over-typed-quotations-in-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!