Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use dynamic types in F#?

.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)
like image 900
Begtostudy Avatar asked Aug 19 '10 11:08

Begtostudy


People also ask

Which methods are not supported for dynamic types?

Extension methods aren't supported by dynamic code.

Is F# dynamic?

Omitting explicit type information does not mean that F# is a dynamically typed language or that values in F# are weakly typed. F# is a statically typed language, which means that the compiler deduces an exact type for each construct during compilation.

Where can you use the dynamic data type?

In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.

Is it good to use dynamic type in C#?

The dynamic type has been added to C# since version 4 as because of the need to improve interoperability with COM (Component Object Model) and other dynamic languages. While that can be achieved with reflection, dynamic provides a natural and more intuitive way to implement the same code.


1 Answers

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.

like image 171
jbtule Avatar answered Sep 21 '22 05:09

jbtule