I canβt find a definition of what calls inside the sequence expression are in the tail position in F #, so I highly recommend not writing code that depends on the semantics of the current implementation, i.e. this behavior is undefined.
For example, trying to enumerate (for example, using Seq.length ), the following sequence causes a stack overflow:
let rec xs() = seq { yield! xs() }
but, as Thomas noted, the following actually works:
let rec xs n = seq { yield n; yield! xs(n+1) }
My advice is to always replace recursive sequence expressions with Seq.unfold . In this case, you probably want to copy the work you are doing (for example, when you go to the left branch, you push the right branch onto the stack in the battery).
FWIW, even a link to the F # language is wrong. It gives the following code to align the tree:
type Tree<'a> = | Tree of 'a * Tree<'a> * Tree<'a> | Leaf of 'a let rec inorder tree = seq { match tree with | Tree(x, left, right) -> yield! inorder left yield x yield! inorder right | Leaf x -> yield x }
Their own code kills F # interactively with stack overflow when it feeds a deep tree to the left.
source share