F#: is mutual recursion between types and functions possible?

ぃ、小莉子 提交于 2019-12-05 07:35:47

This question is difficult to answer without an example

  • If you have mutually recursive types that do not have members, then the types don't need to know about the functions (so you can first define types and then functions).

  • If you have mutually recursive types that have the functions as members, then the members can see each other (across types) and you should be fine

The only tricky case is when you have mutually recursive types, mutually recursive functions and you also want to exposes some functions as members. Then you can use type extensions:

// Declare mutually recursive types 'A' and 'B'
type A(parent:option<B>) =
  member x.Parent = parent

and B(parent:option<A>) =
  member x.Parent = parent

// Declare mutually recursive functions 'countA' and 'countB'
let rec countA (a:A) =
  match a.Parent with None -> 0 | Some b -> (countB b) + 1
and countB (b:B) =
  match b.Parent with None -> 0 | Some a -> (countA a) + 1

// Add the two functions as members of the types
type A with 
  member x.Count = countA x

type B with 
  member x.Count = countB x

In this case, you could just make countA and countB members of the two types, because it would be easier, but if you have more complex code that you want to write as functions, then this is an option.

If everything is written in a single module (in a single file), then the F# compiler compiles type extensions as standard instance members (so it looks just like normal type from the C# point of view). If you declare extensions in a separate module, then they will be compiled as F#-specific extension methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!