开发者

F# top level do binding

I have a file with a module with some routines that take parameters and return unit, these routines have side-effects. I noticed that when accessing these f# routines from c# they're actually properties of type unit and when I try to access 1 property, it runs all properties in the module.

From the F# documentation all top level do bindings are run on type initialization.

What is the preferred way to write functions that should no开发者_运维百科t be run on type initialization but are also not associated with other state i.e. a class with functions and member variables?

Should I put these functions inside a type and just have no records in the type?

Code example:

namespace test_space

open System.Diagnostics;

module test =
    let test_1 =
        Debug.WriteLine ("One")

    let test_2 =
        Debug.WriteLine ("Two")

I'm running this code with C#:

static void Main (string [] args)
{
    Object o;

    o = test.test_2;
}

And the output is:

One

Two


The problem is you didn't create functions but value bindings. test_1 is a value. test_1() is a function of type unit -> unit. Make sure you put () after the function name.


I don't fully understand the scenario you're describing - F# functions declared in a module will generally appear as methods and values will appear as properties. The code that is executed when you first access module (type initialization) is the initialization of values.

If you write just:

module Foo =
  let Operation () = 
    printfn "hello"

...then calling Operation will be a method and calling Foo.Operation() will run the side-effect. If you can post some code that behaves unexpectedly, then someone can explain it.

Anyway, if you want to be sure about the behavior, you can write operations as static members of a class:

type Foo = 
  static member Operation() =
    printfn "hello"

Then you can be sure that F# will compile them as static members of a class in a predictable way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜