これは、実際には F# のProject Euler Problem 14のソリューションです。ただし、より大きな数値の反復シーケンスを計算しようとすると、System.OutOfMemory 例外が発生します。ご覧のとおり、テール コールを使用して再帰関数を記述しています。
ビジュアルスタジオでデバッグしていたため(テールコールが無効になっているため)、StackOverFlowExceptionで問題が発生していました。別の質問でそれを文書化しました。ここでは、リリース モードで実行していますが、これをコンソール アプリとして実行すると、メモリ不足の例外が発生します (Windows XP 上で 4 GB RAM を使用)。
このメモリオーバーフローに自分自身をどのようにコーディングしたかを理解するのに本当に途方に暮れており、誰かが私の方法でエラーを示してくれることを望んでいます。
let E14_interativeSequence x =
let rec calc acc startNum =
match startNum with
| d when d = 1 -> List.rev (d::acc)
| e when e%2 = 0 -> calc (e::acc) (e/2)
| _ -> calc (startNum::acc) (startNum * 3 + 1)
let maxNum pl=
let rec maxPairInternal acc pairList =
match pairList with
| [] -> acc
| x::xs -> if (snd x) > (snd acc) then maxPairInternal x xs
else maxPairInternal acc xs
maxPairInternal (0,0) pl
|> fst
// if I lower this to like [2..99999] it will work.
[2..99999]
|> List.map (fun n -> (n,(calc [] n)))
|> List.map (fun pair -> ((fst pair), (List.length (snd pair))))
|> maxNum
|> (fun x-> Console.WriteLine(x))
編集
回答による提案を考慮して、遅延リストを使用し、Int64 を使用するように書き直しました。
#r "FSharp.PowerPack.dll"
let E14_interativeSequence =
let rec calc acc startNum =
match startNum with
| d when d = 1L -> List.rev (d::acc) |> List.toSeq
| e when e%2L = 0L -> calc (e::acc) (e/2L)
| _ -> calc (startNum::acc) (startNum * 3L + 1L)
let maxNum (lazyPairs:LazyList<System.Int64*System.Int64>) =
let rec maxPairInternal acc (pairs:seq<System.Int64*System.Int64>) =
match pairs with
| :? LazyList<System.Int64*System.Int64> as p ->
match p with
| LazyList.Cons(x,xs)-> if (snd x) > (snd acc) then maxPairInternal x xs
else maxPairInternal acc xs
| _ -> acc
| _ -> failwith("not a lazylist of pairs")
maxPairInternal (0L,0L) lazyPairs
|> fst
{2L..999999L}
|> Seq.map (fun n -> (n,(calc [] n)))
|> Seq.map (fun pair -> ((fst pair), (Convert.ToInt64(Seq.length (snd pair)))))
|> LazyList.ofSeq
|> maxNum
問題を解決します。ただし、より優れたYin Zhuのソリューションも検討します。