F#内联如何工作? [英] How does F# inline work?

查看:66
本文介绍了F#内联如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,使用F#,您可以使用inline关键字在呼叫站点执行类型专门化.那是::

With F# it is my understanding that you can use the inline keyword to perform type specialization at the call site. That is::

val inline (+) : ^a -> ^b -> ^c
      when (^a or ^b) : (static member (+) : ^a * ^b -> ^c)

限制^a^b必须具有静态成员(如op_Addition)或内置基元之一,该静态成员可用于填补空白.

Constrains that ^a or ^b must have a static member like op_Addition, or one of the built in primitives, that can be used to fill in the gap.

因此,如果您有一个带有+的方法,并且将int和short传递为参数,则它将+展开为将内置基元用于int的指令,并且如果您传递了float和一个字节,使用float基本加法操作码.

So if you have a method that has a + and you pass in an int and a short as parameters it unwraps + to an instruction to use the built in primitive for int, and if you pass in a float and a byte it uses the float primitive addition opcode.

在编译时这是如何完成的?您如何在CLR中有一个根据类型切换使用的操作码或方法的方法?

How exactly is this done at compile time? How can you have a method in the CLR that switches what opcode or method it uses based on the type?

Reflection.Emit是否可以实现此行为? 我知道内联是在调用站点执行的,这是否意味着代码不适用于C#?

Is this behavior possible with Reflection.Emit? I understand that the inlining is performed at the call-site, does that mean that the code does not work with C#?

推荐答案

inline所建议,该代码在调用站点处内联.在每个呼叫站点,您都知道具体的类型参数^T,因此该类型的特定代码会插入其中.

As suggested by inline, the code is inlined at the call site. At every call site, you know the concrete type parameter ^T, so the specific code for that type is inserted there.

这是由F#编译器完成的,在其他上下文中(例如C#或Ref.Emit),您很难做到这一点.

This is done by the F# compiler, you can't easily do it in other context (like C# or Ref.Emit).

F#库具有一些内联函数,其他语言仍然可以调用这些函数,这些实现的运行时会根据运行时类型进行动态分配,请参见例如F#Core库代码中prim-types.fsprim-types.fs中的AdditionDynamic代码.

The F# library has some inline functions that can still be called by other languages, the runtime for those implementations does dynamic dispatch based on the runtime type, see e.g. the code for AdditionDynamic in prim-types.fs in the F# Core library code to get a feel.

这篇关于F#内联如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆