.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)
Extension methods aren't supported by dynamic code.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With