我可以在 F# 中使用动态类型吗?

发布于 2024-09-14 21:23:26 字数 544 浏览 2 评论 0原文

.net4.0

mytest.py

def Add (a, b):
    return a+b

我可以在 C# 4 中使用它,如下所示:

        ScriptRuntime runtime = Python.CreateRuntime();
        dynamic script = runtime.UseFile("mytest.py");

        Console.WriteLine(script.Add(1, 3));

但是,如何在 F# 中使用动态?

open System
open Microsoft.Scripting.Hosting
open IronPython.Hosting

let call a b=
    let runtime = Python.CreateRuntime()
    let script = runtime.UseFile("mytest.py")
    script.Add(a,b)

.net4.0

mytest.py

def Add (a, b):
    return a+b

I can use it in C# 4, like this:

        ScriptRuntime runtime = Python.CreateRuntime();
        dynamic script = runtime.UseFile("mytest.py");

        Console.WriteLine(script.Add(1, 3));

But, how can I use dynamic in F#?

open System
open Microsoft.Scripting.Hosting
open IronPython.Hosting

let call a b=
    let runtime = Python.CreateRuntime()
    let script = runtime.UseFile("mytest.py")
    script.Add(a,b)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离旧人 2024-09-21 21:23:26

nuget上有一个模块FSharp.Interop.Dynamic,它实现了动态使用 dlr 的操作员。所以:

open System
open Microsoft.Scripting.Hosting
open IronPython.Hosting
open EkonBenefits.FSharp.Dynamic

let call a b=
    let runtime = Python.CreateRuntime()
    let script = runtime.UseFile("mytest.py")
    script?Add(a,b)

与许多现有的片段相比,它有几个优点。

  • 它使用 Dynamitey 进行 dlr 调用,Dynamitey 实现调用站点的缓存,并且是一个 PCL库
  • 处理返回 void 的方法,如果在设置活页夹时没有丢弃这些结果,则会出现绑定异常。
  • dlr 会自动处理由函数调用委托返回的情况,即兴 fsharp 还允许您对 FSharpFunc 执行相同操作
  • 添加 !?前缀运算符来处理直接调用动态对象和函数,您在运行时没有该类型。

    它是开源的,Apache许可证,你可以查看实现,它包括单元测试 示例案例

There is a module FSharp.Interop.Dynamic, on nuget that implements the dynamic operator using the dlr. So That:

open System
open Microsoft.Scripting.Hosting
open IronPython.Hosting
open EkonBenefits.FSharp.Dynamic

let call a b=
    let runtime = Python.CreateRuntime()
    let script = runtime.UseFile("mytest.py")
    script?Add(a,b)

It has several advantages over a lot of the snippets out there.

  • Performance it uses Dynamitey for the dlr call and Dynamitey implements caching of the callsites and is a PCL library
  • Handles methods that return void, you'd get a binding exception if you didn't discard results of those when the binder was setup.
  • The dlr handles the case of calling a delegate return by a function automatically, impromptu fsharp will also allow you to do the same with an FSharpFunc
  • Adds an !? prefix operator to handle invoking directly dynamic objects and functions you don't have the type at runtime.

    It's open source, Apache license, you can look at the implementation and it includes unit test example cases.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文