F#使用递归列表

Tom*_*res 2 f#

我的代码(下面)因堆栈溢出异常而崩溃.我假设F#不像haskell和dosent与递归列表很好地配合.什么是在F#中处理这样的递归列表的正确方法?我应该把它传递给一个int,所以它有一个确定的大小?

let rec collatz num =
    match num with 
        |x when x % 2 = 0 ->num :: collatz (x/2)                                            
        |x ->               num :: collatz ((x * 3) + 1)

let smallList = collatz(4) |> Seq.take(4)
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 5

对于这样的无限列表,您希望返回一个序列.序列是懒惰的; 列表不是.

let rec collatz num = 
  seq {
    yield num
    match num with 
    | x when x % 2 = 0 -> yield! collatz (x/2)                                            
    | x -> yield! collatz ((x * 3) + 1)
  }

let smallList = 
  collatz 4
  |> Seq.take 4
  |> Seq.toList //[4; 2; 1; 4]
Run Code Online (Sandbox Code Playgroud)