Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Recursive Member Function : "How to Define it correctly"

I it is my understanding that when you define a recursive member function within a type then there is no need to define the function to be recursive. Meaning use of the rec keyword.

however when i do this:

type hello() = class
  member this.recursion(x) =
      match x with
      |10 -> printfn "%A" x
      |_ -> printfn "%A" x
            recursion(x+1)
end

Then i get the error that recursion is not defined.

I have tried this.recursion but then i still get a warning saying:

The recursive object reference 'this' is unused. The presence of a recursive object reference adds runtime initialization checks to members in this and derived types. Consider removing this recursive object reference.

So i am wondering what is the correct way to define a recursive member function within a type?

like image 898
Nulle Avatar asked Jan 20 '17 13:01

Nulle


1 Answers

Yes, they work when defined as members. As you already noticed, you're missing the this at the call site. It should be:

this.recursion(x+1)

But this works well, at least for me:

type hello() = class
  member this.recursion(x) =
      match x with
      |10 -> printfn "%A" x
      |_ -> printfn "%A" x
        this.recursion(x+1)
end

Anyway I would define it internally, as showed in the other answer but inside the method:

type hello() = class
  member this.recursion(x) =
    let rec loop x =
      match x with
      |10 -> printfn "%A" x
      |_ -> printfn "%A" x
            loop (x+1)
    loop x
end
like image 177
Gus Avatar answered Oct 22 '22 01:10

Gus