F#中用Continuation編程避免堆棧溢出
當我接觸的F#編程越多,我用到遞歸的可能性就越大,也正是因為這樣,我時常會遇到堆棧溢出的問題,要想避免堆棧溢出問題,Continuation Style Program(CSP)是唯一的方法。以下我們列出普通的遞歸和CSP的版本代碼進行對比,在這里,關鍵的一點,該方法不會返回,因此它不會在調用的堆棧上創建元素,同時,由于會延遲計算Continuation方法,它不需要被保存在棧元素中:
- module FunctionReturnModule =
- let l = [1..1000000]
- let rec sum l =
- match l with
- | [] -> 0
- | h::t -> h + sum t
- sum l
- module CPSModule =
- let l = [1..1000000]
- let rec sum l cont =
- match l with
- | [] -> cont 0
- | h::t ->
- let afterSum v =
- cont (h+v)
- sum t afterSum
- sum l id
好吧,接下來的問題是如何從普通遞歸的方法得到CSP的遞歸版本呢?以下是我遵循的步驟,記?。浩渲幸恍┲虚g代碼并不能通過編譯。
首先看看我們原始的遞歸代碼:
第一步:
- module FunctionReturnModule =
- let l = [1..1000000]
- let rec sum l =
- match l with
- | [] -> 0
- | h::t ->
- let r = sum t
- h + r
- sum l
第二步:處理遞歸函數中的sum,將cont移動到afterSum中,afterSum方法獲得到參數v并將它傳遞給cont(h+v):
- module CPSModule =
- let l = [1..1000000]
- let rec sum l cont =
- match l with
- | [] -> cont 0
- | h::t ->
- let afterSum v =
- cont (h+v)
- sum t afterSum
- sum l id
那么,接下來讓我們使用相同的方法來遍歷樹,下面先列出樹的定義:
- type NodeType = int
- type BinaryTree =
- | Nil
- | Node of NodeType * BinaryTree * BinaryTree
最終的結果如下:
- module TreeModule =
- let rec sum tree =
- match tree with
- | Nil -> 0
- | Node(v, l, r) ->
- let sumL = sum l
- let sumR = sum r
- v + sumL + sumR
- sum deepTree
- module TreeCSPModule =
- let rec sum tree cont =
- match tree with
- | Nil -> cont 0
- | Node(v, l, r) ->
- let afterLeft lValue =
- let afterRight rValue =
- cont (v+lValue+rValue)
- sum r afterRight
- sum l afterLeft
- sum deepTree id
開始使用相同的步驟將它轉換成CSP方式:
首先切入Continuation函數:
- module TreeModule =
- let rec sum tree cont =
- match tree with
- | Nil -> 0
- | Node(v, l, r) ->
- let sumL = sum l
- let sumR = sum r
- cont (v + sumL + sumR)
- sum deepTree
第一步:處理sumR,將cont方法移動到afterRight中并將它傳給sum r:
- module TreeModule =
- let rec sum tree cont =
- match tree with
- | Nil -> 0
- | Node(v, l, r) ->
- let sumL = sum l
- // let sumR = sum r
- let afterRight rValue =
- cont (v + sumL + rValue)
- sum r afterRight
- sum deepTree
第二步:處理sumL:
- module TreeModule =
- let rec sum tree cont =
- match tree with
- | Nil -> 0
- | Node(v, l, r) ->
- //let sumL = sum l
- let afterLeft lValue =
- let afterRight rValue =
- cont (v + lValue + rValue)
- sum r afterRight
- sum l afterLeft
- sum deepTree
結束了,接下來讓我們用下面的代碼進行測試吧:
- let tree n =
- let mutable subTree = Node(1, Nil, Nil)
- for i=0 to n do
- subTree <- Node(1, subTree, Nil)
- subTree
- let deepTree = tree 1000000