4
我知道遞歸函數是F#中的一項強大技術。我的問題是:是否有退出語句,可以跳出遞歸函數,就像命令式語言一樣。例如,將一個節點插入二叉樹。F#是否有循環退出語句?
type Tree<'a> when 'a :> IComparable<'a> =
| Nil
| Leaf of 'a
| Node of Tree<'a> * 'a * Tree<'a>
let tt2 = Node(
Node(Leaf "D", "B",Node(Leaf "G", "E", Leaf "H")),
"A",
Node(Nil, "C", Node(Nil, "F", Leaf "I")))
let rec contains (x : #IComparable<'a>) = function
| Nil -> false
| Leaf y -> if x.CompareTo(y) = 0 then true else false
| Node(l, y, r) ->
match l, y, r with
| l, y, Nil -> if x.CompareTo(y) = 0 then true else contains x l
| Nil,y, r -> if x.CompareTo(y) = 0 then true else contains x r
| _ -> if x.CompareTo(y) = 0 then true
else contains x r |>ignore
contains x l
let xx = contains "C" tt2 //It is wrong answer.
感謝系列提:-)但應當指出,這樣做會影響到性能的 - 所以,如果你想要一些DSL更有用類似於您關心表達能力的代碼,而不是低級函數實現。 –
是的,當性能很關鍵時,應該去定製遞歸函數。 – pad