What is a period (.) In the F # method

Sorry for the vague description, could not find a better way to clarify it.

I start with F # and, like many others, I translated my problems with Euler into F #. I like to run my code with tests, and I also like the FsUnit style. Using this example, I did this:

open System open NUnit.Framework open FsUnit type EulerProblem() = member this.problem1 = Seq.init 999 (fun n -> n + 1) |> Seq.filter (fun n -> n % 3 = 0 || n % 5 = 0) |> Seq.sum [<TestFixture>] type ``Given an Euler problem`` () = let euler = new EulerProblem() [<Test>] member test. ``when I try to solve #1 should return [the magic number]`` ()= euler.problem1 |> should equal [the magic number] 

This works, but I can't figure out what the period after the test method does. If I take it, the compiler complains, saying:

This instance member needs a parameter to represent the called object. Make element static or use x.Member (args) record element

Sorry if this is trivial, and maybe I am not using the correct wording, but cannot get an answer from Google.

thanks

+4
source share
2 answers

If you are familiar with C # or Java or C ++, you can refer to an instance of the class using the reserved word this in the members of the instance. In F # you must explicitly specify a class instance name for each member definition and in the FsUnit example, this name is just test , but it is not actually used. You could write a test method in the same way as

 [<Test>] member this. ``when I try to solve #1 should return [the magic number]`` ()= euler.problem1 |> should equal [the magic number] 

But note that nowadays, both xUnit.net and NUnit allow you to use their attributes [<Fact>] and [<Test>] respectively, for marking tests that allow you to link functions inside modules without the need for TestFixture and those that are much better suited for F #. So, for example, the test you gave may, and in my opinion, should be written as:

 module EulerProblemTests () = [<Test>] let ``when I try to solve #1 should return [the magic number]`` () = let euler = new EulerProblem() euler.problem1 |> should equal [the magic number] 

In addition, you probably do not want to create your own solutions to problems as type members like EulerProblem , but as functions inside a module.

+4
source

It is still a class, so each member must be static or have "this".

In your test, "test" contains "this" for the member.

Typically, a class will look like this:

 type ClassName() = member thisname.MethodName() = DoSomeStuff |> DoMoreStuff 

Over time, the word "test" was used; without it, he does not know what this member is.

+2
source

Source: https://habr.com/ru/post/1346490/


All Articles