Does F # have a loop exit statement?

I know that a recursive function is a powerful method in F #. My question is: is there an exit instruction that can jump out of recursive functions, just like imperative languages. For example, insert node into a binary tree.

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 xl | Nil,y, r -> if x.CompareTo(y) = 0 then true else contains xr | _ -> if x.CompareTo(y) = 0 then true else contains xr |>ignore contains xl let xx = contains "C" tt2 //It is wrong answer. 
+4
source share
1 answer

Is there an exit instruction that can jump out of recursive functions, as well as imperative languages.

No. The reason itself is that you can encode an imperative break / return with recursive functions and pattern matching. If you want to break, just return the value, otherwise call another recursive call.

This question is more suitable for querying higher order functions. When you need an early exit from higher order functions, writing a custom recursive function is the way to go. If you're interested in imperative constructs in F #, take a look at the great @Tomas series .

Your function will go to any branch when the condition is defined. The only problem is that you should not discard contain xr in the second and last line.

You can remove unnecessary if/else for clarity.

 let rec contains (x : #IComparable<'a>) = function | Nil -> false | Leaf y -> x.CompareTo(y) = 0 | Node(l, y, r) -> match l, y, r with | l, y, Nil -> x.CompareTo(y) = 0 || contains xl | Nil,y, r -> x.CompareTo(y) = 0 || contains xr | _ -> x.CompareTo(y) = 0 || contains xl || contains xr 
+10
source

All Articles