[英]How to get the 2 last values from a list in recursion and in tail-recursion?
[英]F# tree leaves to list with continuation tail-recursion
我有一個有樹枝和樹葉的類型樹。 我想獲得一個葉子值列表。 到目前為止,我只能計算分支機構。
我的樹:
type 'a tr =
| Leaf of 'a
| Branch of 'a tr * 'a tr
我的代碼:
let getList (tr:float tr)=
let rec toList tree acc =
match tree with
| Leaf _ -> acc 0
| Branch (tl,tr) -> toList tl (fun vl -> toList tr (fun vr -> acc(vl+vr+1)))
toList tr id
輸入:
let test=Branch (Leaf 1.2, Branch(Leaf 1.2, Branch(Branch(Leaf 4.5, Leaf 6.6), Leaf 5.4)))
getList test
結果,我想得到一個清單:
[1.2; 1.2; 4.5; 6.6; 5.4]
我嘗試過類似的一些變化,但沒有成功。
| Branch (tl,tr) -> toList tl (fun vl -> toList tr (fun vr -> (vl::vr)::acc))
toList tr []
任何幫助,將不勝感激。
這是由於你的簽名為(int - >'a)的延續函數(acc)如果你想獲得一個展平列表,那么匯總函數簽名應該是('list - >'b)
let getList tree =
let rec toList tree cont =
match tree with
| Leaf a -> cont [a]
| Branch (left, right) ->
toList left (fun l ->
toList right (fun r ->
cont (l @ r)))
toList tree id
編輯; 這應該更有效率
let getList tree =
let rec toList tree cont acc =
match tree with
| Leaf a -> cont (a :: acc)
| Branch (left, right) -> toList left (toList right cont) acc
toList tree id [] |> List.rev
請注意,您的樹類型不能表示只有一個子節點的節點。 類型應該是:
type Tree<'T> =
| Leaf of 'T
| OnlyOne of Tree<'T>
| Both of Tree<'T> * Tree<'T>
要使用尾遞歸與延續,請使用延續功能 ,而不是ACC umulator:
let leaves tree =
let rec collect tree cont =
match tree with
| Leaf x -> cont [x]
| OnlyOne tree -> collect tree cont
| Both (leftTree, rightTree) ->
collect leftTree (fun leftAcc ->
collect rightTree (fun rightAcc ->
leftAcc @ rightAcc |> cont))
collect tree id
P / S:你的命名不是很好: tr
含義太多了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.